babylon.max.js 4.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390
  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. /**
  20. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  21. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  22. */
  23. var EffectFallbacks = /** @class */ (function () {
  24. function EffectFallbacks() {
  25. this._defines = {};
  26. this._currentRank = 32;
  27. this._maxRank = -1;
  28. }
  29. /**
  30. * Removes the fallback from the bound mesh.
  31. */
  32. EffectFallbacks.prototype.unBindMesh = function () {
  33. this._mesh = null;
  34. };
  35. /**
  36. * Adds a fallback on the specified property.
  37. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  38. * @param define The name of the define in the shader
  39. */
  40. EffectFallbacks.prototype.addFallback = function (rank, define) {
  41. if (!this._defines[rank]) {
  42. if (rank < this._currentRank) {
  43. this._currentRank = rank;
  44. }
  45. if (rank > this._maxRank) {
  46. this._maxRank = rank;
  47. }
  48. this._defines[rank] = new Array();
  49. }
  50. this._defines[rank].push(define);
  51. };
  52. /**
  53. * Sets the mesh to use CPU skinning when needing to fallback.
  54. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  55. * @param mesh The mesh to use the fallbacks.
  56. */
  57. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  58. this._mesh = mesh;
  59. if (rank < this._currentRank) {
  60. this._currentRank = rank;
  61. }
  62. if (rank > this._maxRank) {
  63. this._maxRank = rank;
  64. }
  65. };
  66. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  67. /**
  68. * Checks to see if more fallbacks are still availible.
  69. */
  70. get: function () {
  71. return this._currentRank <= this._maxRank;
  72. },
  73. enumerable: true,
  74. configurable: true
  75. });
  76. /**
  77. * Removes the defines that shoould be removed when falling back.
  78. * @param currentDefines defines the current define statements for the shader.
  79. * @param effect defines the current effect we try to compile
  80. * @returns The resulting defines with defines of the current rank removed.
  81. */
  82. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  83. // First we try to switch to CPU skinning
  84. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  85. this._mesh.computeBonesUsingShaders = false;
  86. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  87. var scene = this._mesh.getScene();
  88. for (var index = 0; index < scene.meshes.length; index++) {
  89. var otherMesh = scene.meshes[index];
  90. if (!otherMesh.material) {
  91. continue;
  92. }
  93. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  94. continue;
  95. }
  96. if (otherMesh.material.getEffect() === effect) {
  97. otherMesh.computeBonesUsingShaders = false;
  98. }
  99. else {
  100. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  101. var subMesh = _a[_i];
  102. var subMeshEffect = subMesh.effect;
  103. if (subMeshEffect === effect) {
  104. otherMesh.computeBonesUsingShaders = false;
  105. break;
  106. }
  107. }
  108. }
  109. }
  110. }
  111. else {
  112. var currentFallbacks = this._defines[this._currentRank];
  113. if (currentFallbacks) {
  114. for (var index = 0; index < currentFallbacks.length; index++) {
  115. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  116. }
  117. }
  118. this._currentRank++;
  119. }
  120. return currentDefines;
  121. };
  122. return EffectFallbacks;
  123. }());
  124. BABYLON.EffectFallbacks = EffectFallbacks;
  125. /**
  126. * Options to be used when creating an effect.
  127. */
  128. var EffectCreationOptions = /** @class */ (function () {
  129. function EffectCreationOptions() {
  130. }
  131. return EffectCreationOptions;
  132. }());
  133. BABYLON.EffectCreationOptions = EffectCreationOptions;
  134. /**
  135. * Effect containing vertex and fragment shader that can be executed on an object.
  136. */
  137. var Effect = /** @class */ (function () {
  138. /**
  139. * Instantiates an effect.
  140. * An effect can be used to create/manage/execute vertex and fragment shaders.
  141. * @param baseName Name of the effect.
  142. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  143. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  144. * @param samplers List of sampler variables that will be passed to the shader.
  145. * @param engine Engine to be used to render the effect
  146. * @param defines Define statements to be added to the shader.
  147. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  148. * @param onCompiled Callback that will be called when the shader is compiled.
  149. * @param onError Callback that will be called if an error occurs during shader compilation.
  150. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  151. */
  152. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  153. if (samplers === void 0) { samplers = null; }
  154. if (defines === void 0) { defines = null; }
  155. if (fallbacks === void 0) { fallbacks = null; }
  156. if (onCompiled === void 0) { onCompiled = null; }
  157. if (onError === void 0) { onError = null; }
  158. var _this = this;
  159. /**
  160. * Unique ID of the effect.
  161. */
  162. this.uniqueId = 0;
  163. /**
  164. * Observable that will be called when the shader is compiled.
  165. */
  166. this.onCompileObservable = new BABYLON.Observable();
  167. /**
  168. * Observable that will be called if an error occurs during shader compilation.
  169. */
  170. this.onErrorObservable = new BABYLON.Observable();
  171. /**
  172. * Observable that will be called when effect is bound.
  173. */
  174. this.onBindObservable = new BABYLON.Observable();
  175. this._uniformBuffersNames = {};
  176. this._isReady = false;
  177. this._compilationError = "";
  178. this.name = baseName;
  179. if (attributesNamesOrOptions.attributes) {
  180. var options = attributesNamesOrOptions;
  181. this._engine = uniformsNamesOrEngine;
  182. this._attributesNames = options.attributes;
  183. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  184. this._samplers = options.samplers;
  185. this.defines = options.defines;
  186. this.onError = options.onError;
  187. this.onCompiled = options.onCompiled;
  188. this._fallbacks = options.fallbacks;
  189. this._indexParameters = options.indexParameters;
  190. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  191. if (options.uniformBuffersNames) {
  192. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  193. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  194. }
  195. }
  196. }
  197. else {
  198. this._engine = engine;
  199. this.defines = defines;
  200. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  201. this._samplers = samplers;
  202. this._attributesNames = attributesNamesOrOptions;
  203. this.onError = onError;
  204. this.onCompiled = onCompiled;
  205. this._indexParameters = indexParameters;
  206. this._fallbacks = fallbacks;
  207. }
  208. this.uniqueId = Effect._uniqueIdSeed++;
  209. var vertexSource;
  210. var fragmentSource;
  211. if (baseName.vertexElement) {
  212. vertexSource = document.getElementById(baseName.vertexElement);
  213. if (!vertexSource) {
  214. vertexSource = baseName.vertexElement;
  215. }
  216. }
  217. else {
  218. vertexSource = baseName.vertex || baseName;
  219. }
  220. if (baseName.fragmentElement) {
  221. fragmentSource = document.getElementById(baseName.fragmentElement);
  222. if (!fragmentSource) {
  223. fragmentSource = baseName.fragmentElement;
  224. }
  225. }
  226. else {
  227. fragmentSource = baseName.fragment || baseName;
  228. }
  229. var finalVertexCode;
  230. this._loadVertexShaderAsync(vertexSource)
  231. .then(function (vertexCode) {
  232. return _this._processIncludesAsync(vertexCode);
  233. })
  234. .then(function (vertexCodeWithIncludes) {
  235. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  236. return _this._loadFragmentShaderAsync(fragmentSource);
  237. })
  238. .then(function (fragmentCode) {
  239. return _this._processIncludesAsync(fragmentCode);
  240. })
  241. .then(function (fragmentCodeWithIncludes) {
  242. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  243. if (baseName) {
  244. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  245. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  246. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  247. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  248. }
  249. else {
  250. _this._vertexSourceCode = finalVertexCode;
  251. _this._fragmentSourceCode = migratedFragmentCode;
  252. }
  253. _this._prepareEffect();
  254. });
  255. }
  256. Object.defineProperty(Effect.prototype, "key", {
  257. /**
  258. * Unique key for this effect
  259. */
  260. get: function () {
  261. return this._key;
  262. },
  263. enumerable: true,
  264. configurable: true
  265. });
  266. /**
  267. * If the effect has been compiled and prepared.
  268. * @returns if the effect is compiled and prepared.
  269. */
  270. Effect.prototype.isReady = function () {
  271. return this._isReady;
  272. };
  273. /**
  274. * The engine the effect was initialized with.
  275. * @returns the engine.
  276. */
  277. Effect.prototype.getEngine = function () {
  278. return this._engine;
  279. };
  280. /**
  281. * The compiled webGL program for the effect
  282. * @returns the webGL program.
  283. */
  284. Effect.prototype.getProgram = function () {
  285. return this._program;
  286. };
  287. /**
  288. * The set of names of attribute variables for the shader.
  289. * @returns An array of attribute names.
  290. */
  291. Effect.prototype.getAttributesNames = function () {
  292. return this._attributesNames;
  293. };
  294. /**
  295. * Returns the attribute at the given index.
  296. * @param index The index of the attribute.
  297. * @returns The location of the attribute.
  298. */
  299. Effect.prototype.getAttributeLocation = function (index) {
  300. return this._attributes[index];
  301. };
  302. /**
  303. * Returns the attribute based on the name of the variable.
  304. * @param name of the attribute to look up.
  305. * @returns the attribute location.
  306. */
  307. Effect.prototype.getAttributeLocationByName = function (name) {
  308. var index = this._attributesNames.indexOf(name);
  309. return this._attributes[index];
  310. };
  311. /**
  312. * The number of attributes.
  313. * @returns the numnber of attributes.
  314. */
  315. Effect.prototype.getAttributesCount = function () {
  316. return this._attributes.length;
  317. };
  318. /**
  319. * Gets the index of a uniform variable.
  320. * @param uniformName of the uniform to look up.
  321. * @returns the index.
  322. */
  323. Effect.prototype.getUniformIndex = function (uniformName) {
  324. return this._uniformsNames.indexOf(uniformName);
  325. };
  326. /**
  327. * Returns the attribute based on the name of the variable.
  328. * @param uniformName of the uniform to look up.
  329. * @returns the location of the uniform.
  330. */
  331. Effect.prototype.getUniform = function (uniformName) {
  332. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  333. };
  334. /**
  335. * Returns an array of sampler variable names
  336. * @returns The array of sampler variable neames.
  337. */
  338. Effect.prototype.getSamplers = function () {
  339. return this._samplers;
  340. };
  341. /**
  342. * The error from the last compilation.
  343. * @returns the error string.
  344. */
  345. Effect.prototype.getCompilationError = function () {
  346. return this._compilationError;
  347. };
  348. /**
  349. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  350. * @param func The callback to be used.
  351. */
  352. Effect.prototype.executeWhenCompiled = function (func) {
  353. if (this.isReady()) {
  354. func(this);
  355. return;
  356. }
  357. this.onCompileObservable.add(function (effect) {
  358. func(effect);
  359. });
  360. };
  361. /** @ignore */
  362. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  363. if (BABYLON.Tools.IsWindowObjectExist()) {
  364. // DOM element ?
  365. if (vertex instanceof HTMLElement) {
  366. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  367. return Promise.resolve(vertexCode);
  368. }
  369. }
  370. // Base64 encoded ?
  371. if (vertex.substr(0, 7) === "base64:") {
  372. var vertexBinary = window.atob(vertex.substr(7));
  373. return Promise.resolve(vertexBinary);
  374. }
  375. // Is in local store ?
  376. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  377. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  378. }
  379. var vertexShaderUrl;
  380. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  381. vertexShaderUrl = vertex;
  382. }
  383. else {
  384. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  385. }
  386. // Vertex shader
  387. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  388. };
  389. /** @ignore */
  390. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  391. if (BABYLON.Tools.IsWindowObjectExist()) {
  392. // DOM element ?
  393. if (fragment instanceof HTMLElement) {
  394. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  395. return Promise.resolve(fragmentCode);
  396. }
  397. }
  398. // Base64 encoded ?
  399. if (fragment.substr(0, 7) === "base64:") {
  400. var fragmentBinary = window.atob(fragment.substr(7));
  401. return Promise.resolve(fragmentBinary);
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  406. }
  407. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  408. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  409. }
  410. var fragmentShaderUrl;
  411. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  412. fragmentShaderUrl = fragment;
  413. }
  414. else {
  415. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  416. }
  417. // Fragment shader
  418. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  419. };
  420. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  421. // Rebuild shaders source code
  422. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  423. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  424. vertexCode = prefix + vertexCode;
  425. fragmentCode = prefix + fragmentCode;
  426. // Number lines of shaders source code
  427. var i = 2;
  428. var regex = /\n/gm;
  429. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  430. i = 2;
  431. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  432. // Dump shaders name and formatted source code
  433. if (this.name.vertexElement) {
  434. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  435. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  436. }
  437. else if (this.name.vertex) {
  438. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  439. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  440. }
  441. else {
  442. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  443. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  444. }
  445. };
  446. ;
  447. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  448. var preparedSourceCode = this._processPrecision(sourceCode);
  449. if (this._engine.webGLVersion == 1) {
  450. return preparedSourceCode;
  451. }
  452. // Already converted
  453. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  454. return preparedSourceCode.replace("#version 300 es", "");
  455. }
  456. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  457. // Remove extensions
  458. // #extension GL_OES_standard_derivatives : enable
  459. // #extension GL_EXT_shader_texture_lod : enable
  460. // #extension GL_EXT_frag_depth : enable
  461. // #extension GL_EXT_draw_buffers : require
  462. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  463. var result = preparedSourceCode.replace(regex, "");
  464. // Migrate to GLSL v300
  465. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  466. result = result.replace(/attribute[ \t]/g, "in ");
  467. result = result.replace(/[ \t]attribute/g, " in");
  468. if (isFragment) {
  469. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  470. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  471. result = result.replace(/texture2D\s*\(/g, "texture(");
  472. result = result.replace(/textureCube\s*\(/g, "texture(");
  473. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  474. result = result.replace(/gl_FragColor/g, "glFragColor");
  475. result = result.replace(/gl_FragData/g, "glFragData");
  476. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  477. }
  478. return result;
  479. };
  480. Effect.prototype._processIncludesAsync = function (sourceCode) {
  481. var _this = this;
  482. return new Promise(function (resolve, reject) {
  483. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  484. var match = regex.exec(sourceCode);
  485. var returnValue = sourceCode;
  486. while (match != null) {
  487. var includeFile = match[1];
  488. // Uniform declaration
  489. if (includeFile.indexOf("__decl__") !== -1) {
  490. includeFile = includeFile.replace(/__decl__/, "");
  491. if (_this._engine.supportsUniformBuffers) {
  492. includeFile = includeFile.replace(/Vertex/, "Ubo");
  493. includeFile = includeFile.replace(/Fragment/, "Ubo");
  494. }
  495. includeFile = includeFile + "Declaration";
  496. }
  497. if (Effect.IncludesShadersStore[includeFile]) {
  498. // Substitution
  499. var includeContent = Effect.IncludesShadersStore[includeFile];
  500. if (match[2]) {
  501. var splits = match[3].split(",");
  502. for (var index = 0; index < splits.length; index += 2) {
  503. var source = new RegExp(splits[index], "g");
  504. var dest = splits[index + 1];
  505. includeContent = includeContent.replace(source, dest);
  506. }
  507. }
  508. if (match[4]) {
  509. var indexString = match[5];
  510. if (indexString.indexOf("..") !== -1) {
  511. var indexSplits = indexString.split("..");
  512. var minIndex = parseInt(indexSplits[0]);
  513. var maxIndex = parseInt(indexSplits[1]);
  514. var sourceIncludeContent = includeContent.slice(0);
  515. includeContent = "";
  516. if (isNaN(maxIndex)) {
  517. maxIndex = _this._indexParameters[indexSplits[1]];
  518. }
  519. for (var i = minIndex; i < maxIndex; i++) {
  520. if (!_this._engine.supportsUniformBuffers) {
  521. // Ubo replacement
  522. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  523. return p1 + "{X}";
  524. });
  525. }
  526. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  527. }
  528. }
  529. else {
  530. if (!_this._engine.supportsUniformBuffers) {
  531. // Ubo replacement
  532. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  533. return p1 + "{X}";
  534. });
  535. }
  536. includeContent = includeContent.replace(/\{X\}/g, indexString);
  537. }
  538. }
  539. // Replace
  540. returnValue = returnValue.replace(match[0], includeContent);
  541. }
  542. else {
  543. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  544. _this._engine._loadFileAsync(includeShaderUrl)
  545. .then(function (fileContent) {
  546. Effect.IncludesShadersStore[includeFile] = fileContent;
  547. return _this._processIncludesAsync(returnValue);
  548. })
  549. .then(function (returnValue) {
  550. resolve(returnValue);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. resolve(returnValue);
  557. });
  558. };
  559. Effect.prototype._processPrecision = function (source) {
  560. if (source.indexOf("precision highp float") === -1) {
  561. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  562. source = "precision mediump float;\n" + source;
  563. }
  564. else {
  565. source = "precision highp float;\n" + source;
  566. }
  567. }
  568. else {
  569. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  570. source = source.replace("precision highp float", "precision mediump float");
  571. }
  572. }
  573. return source;
  574. };
  575. /**
  576. * Recompiles the webGL program
  577. * @param vertexSourceCode The source code for the vertex shader.
  578. * @param fragmentSourceCode The source code for the fragment shader.
  579. * @param onCompiled Callback called when completed.
  580. * @param onError Callback called on error.
  581. */
  582. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  583. var _this = this;
  584. this._isReady = false;
  585. this._vertexSourceCodeOverride = vertexSourceCode;
  586. this._fragmentSourceCodeOverride = fragmentSourceCode;
  587. this.onError = function (effect, error) {
  588. if (onError) {
  589. onError(error);
  590. }
  591. };
  592. this.onCompiled = function () {
  593. var scenes = _this.getEngine().scenes;
  594. for (var i = 0; i < scenes.length; i++) {
  595. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  596. }
  597. if (onCompiled) {
  598. onCompiled(_this._program);
  599. }
  600. };
  601. this._fallbacks = null;
  602. this._prepareEffect();
  603. };
  604. /**
  605. * Gets the uniform locations of the the specified variable names
  606. * @param names THe names of the variables to lookup.
  607. * @returns Array of locations in the same order as variable names.
  608. */
  609. Effect.prototype.getSpecificUniformLocations = function (names) {
  610. var engine = this._engine;
  611. return engine.getUniforms(this._program, names);
  612. };
  613. /**
  614. * Prepares the effect
  615. */
  616. Effect.prototype._prepareEffect = function () {
  617. var attributesNames = this._attributesNames;
  618. var defines = this.defines;
  619. var fallbacks = this._fallbacks;
  620. this._valueCache = {};
  621. var previousProgram = this._program;
  622. try {
  623. var engine = this._engine;
  624. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  625. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  626. }
  627. else {
  628. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  629. }
  630. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  631. if (engine.supportsUniformBuffers) {
  632. for (var name in this._uniformBuffersNames) {
  633. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  634. }
  635. }
  636. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  637. this._attributes = engine.getAttributes(this._program, attributesNames);
  638. var index;
  639. for (index = 0; index < this._samplers.length; index++) {
  640. var sampler = this.getUniform(this._samplers[index]);
  641. if (sampler == null) {
  642. this._samplers.splice(index, 1);
  643. index--;
  644. }
  645. }
  646. engine.bindSamplers(this);
  647. this._compilationError = "";
  648. this._isReady = true;
  649. if (this.onCompiled) {
  650. this.onCompiled(this);
  651. }
  652. this.onCompileObservable.notifyObservers(this);
  653. this.onCompileObservable.clear();
  654. // Unbind mesh reference in fallbacks
  655. if (this._fallbacks) {
  656. this._fallbacks.unBindMesh();
  657. }
  658. if (previousProgram) {
  659. this.getEngine()._deleteProgram(previousProgram);
  660. }
  661. }
  662. catch (e) {
  663. this._compilationError = e.message;
  664. // Let's go through fallbacks then
  665. BABYLON.Tools.Error("Unable to compile effect:");
  666. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  667. return " " + uniform;
  668. }));
  669. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  670. return " " + attribute;
  671. }));
  672. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  673. BABYLON.Tools.Error("Error: " + this._compilationError);
  674. if (previousProgram) {
  675. this._program = previousProgram;
  676. this._isReady = true;
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. }
  682. if (fallbacks && fallbacks.isMoreFallbacks) {
  683. BABYLON.Tools.Error("Trying next fallback.");
  684. this.defines = fallbacks.reduce(this.defines, this);
  685. this._prepareEffect();
  686. }
  687. else {
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. this.onErrorObservable.clear();
  693. // Unbind mesh reference in fallbacks
  694. if (this._fallbacks) {
  695. this._fallbacks.unBindMesh();
  696. }
  697. }
  698. }
  699. };
  700. Object.defineProperty(Effect.prototype, "isSupported", {
  701. /**
  702. * Checks if the effect is supported. (Must be called after compilation)
  703. */
  704. get: function () {
  705. return this._compilationError === "";
  706. },
  707. enumerable: true,
  708. configurable: true
  709. });
  710. /**
  711. * Binds a texture to the engine to be used as output of the shader.
  712. * @param channel Name of the output variable.
  713. * @param texture Texture to bind.
  714. */
  715. Effect.prototype._bindTexture = function (channel, texture) {
  716. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  717. };
  718. /**
  719. * Sets a texture on the engine to be used in the shader.
  720. * @param channel Name of the sampler variable.
  721. * @param texture Texture to set.
  722. */
  723. Effect.prototype.setTexture = function (channel, texture) {
  724. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  725. };
  726. /**
  727. * Sets an array of textures on the engine to be used in the shader.
  728. * @param channel Name of the variable.
  729. * @param textures Textures to set.
  730. */
  731. Effect.prototype.setTextureArray = function (channel, textures) {
  732. if (this._samplers.indexOf(channel + "Ex") === -1) {
  733. var initialPos = this._samplers.indexOf(channel);
  734. for (var index = 1; index < textures.length; index++) {
  735. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  736. }
  737. }
  738. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  739. };
  740. /**
  741. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  742. * @param channel Name of the sampler variable.
  743. * @param postProcess Post process to get the input texture from.
  744. */
  745. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  746. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  747. };
  748. /** @ignore */
  749. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  750. var cache = this._valueCache[uniformName];
  751. var flag = matrix.updateFlag;
  752. if (cache !== undefined && cache === flag) {
  753. return false;
  754. }
  755. this._valueCache[uniformName] = flag;
  756. return true;
  757. };
  758. /** @ignore */
  759. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  760. var cache = this._valueCache[uniformName];
  761. if (!cache) {
  762. cache = [x, y];
  763. this._valueCache[uniformName] = cache;
  764. return true;
  765. }
  766. var changed = false;
  767. if (cache[0] !== x) {
  768. cache[0] = x;
  769. changed = true;
  770. }
  771. if (cache[1] !== y) {
  772. cache[1] = y;
  773. changed = true;
  774. }
  775. return changed;
  776. };
  777. /** @ignore */
  778. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  779. var cache = this._valueCache[uniformName];
  780. if (!cache) {
  781. cache = [x, y, z];
  782. this._valueCache[uniformName] = cache;
  783. return true;
  784. }
  785. var changed = false;
  786. if (cache[0] !== x) {
  787. cache[0] = x;
  788. changed = true;
  789. }
  790. if (cache[1] !== y) {
  791. cache[1] = y;
  792. changed = true;
  793. }
  794. if (cache[2] !== z) {
  795. cache[2] = z;
  796. changed = true;
  797. }
  798. return changed;
  799. };
  800. /** @ignore */
  801. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  802. var cache = this._valueCache[uniformName];
  803. if (!cache) {
  804. cache = [x, y, z, w];
  805. this._valueCache[uniformName] = cache;
  806. return true;
  807. }
  808. var changed = false;
  809. if (cache[0] !== x) {
  810. cache[0] = x;
  811. changed = true;
  812. }
  813. if (cache[1] !== y) {
  814. cache[1] = y;
  815. changed = true;
  816. }
  817. if (cache[2] !== z) {
  818. cache[2] = z;
  819. changed = true;
  820. }
  821. if (cache[3] !== w) {
  822. cache[3] = w;
  823. changed = true;
  824. }
  825. return changed;
  826. };
  827. /**
  828. * Binds a buffer to a uniform.
  829. * @param buffer Buffer to bind.
  830. * @param name Name of the uniform variable to bind to.
  831. */
  832. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  833. var bufferName = this._uniformBuffersNames[name];
  834. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  835. return;
  836. }
  837. Effect._baseCache[bufferName] = buffer;
  838. this._engine.bindUniformBufferBase(buffer, bufferName);
  839. };
  840. /**
  841. * Binds block to a uniform.
  842. * @param blockName Name of the block to bind.
  843. * @param index Index to bind.
  844. */
  845. Effect.prototype.bindUniformBlock = function (blockName, index) {
  846. this._engine.bindUniformBlock(this._program, blockName, index);
  847. };
  848. /**
  849. * Sets an interger value on a uniform variable.
  850. * @param uniformName Name of the variable.
  851. * @param value Value to be set.
  852. * @returns this effect.
  853. */
  854. Effect.prototype.setInt = function (uniformName, value) {
  855. var cache = this._valueCache[uniformName];
  856. if (cache !== undefined && cache === value)
  857. return this;
  858. this._valueCache[uniformName] = value;
  859. this._engine.setInt(this.getUniform(uniformName), value);
  860. return this;
  861. };
  862. /**
  863. * Sets an int array on a uniform variable.
  864. * @param uniformName Name of the variable.
  865. * @param array array to be set.
  866. * @returns this effect.
  867. */
  868. Effect.prototype.setIntArray = function (uniformName, array) {
  869. this._valueCache[uniformName] = null;
  870. this._engine.setIntArray(this.getUniform(uniformName), array);
  871. return this;
  872. };
  873. /**
  874. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  875. * @param uniformName Name of the variable.
  876. * @param array array to be set.
  877. * @returns this effect.
  878. */
  879. Effect.prototype.setIntArray2 = function (uniformName, array) {
  880. this._valueCache[uniformName] = null;
  881. this._engine.setIntArray2(this.getUniform(uniformName), array);
  882. return this;
  883. };
  884. /**
  885. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  886. * @param uniformName Name of the variable.
  887. * @param array array to be set.
  888. * @returns this effect.
  889. */
  890. Effect.prototype.setIntArray3 = function (uniformName, array) {
  891. this._valueCache[uniformName] = null;
  892. this._engine.setIntArray3(this.getUniform(uniformName), array);
  893. return this;
  894. };
  895. /**
  896. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray4 = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray4(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * Sets an float array on a uniform variable.
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setFloatArray = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setFloatArray(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * Sets an array on a uniform variable.
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setArray = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setArray(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setArray2 = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setArray2(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setArray3 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setArray3(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray4 = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray4(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * Sets matrices on a uniform variable.
  996. * @param uniformName Name of the variable.
  997. * @param matrices matrices to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1001. if (!matrices) {
  1002. return this;
  1003. }
  1004. this._valueCache[uniformName] = null;
  1005. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1006. return this;
  1007. };
  1008. /**
  1009. * Sets matrix on a uniform variable.
  1010. * @param uniformName Name of the variable.
  1011. * @param matrix matrix to be set.
  1012. * @returns this effect.
  1013. */
  1014. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1015. if (this._cacheMatrix(uniformName, matrix)) {
  1016. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1017. }
  1018. return this;
  1019. };
  1020. /**
  1021. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1022. * @param uniformName Name of the variable.
  1023. * @param matrix matrix to be set.
  1024. * @returns this effect.
  1025. */
  1026. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1027. this._valueCache[uniformName] = null;
  1028. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1029. return this;
  1030. };
  1031. /**
  1032. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1033. * @param uniformName Name of the variable.
  1034. * @param matrix matrix to be set.
  1035. * @returns this effect.
  1036. */
  1037. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1038. this._valueCache[uniformName] = null;
  1039. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1040. return this;
  1041. };
  1042. /**
  1043. * Sets a float on a uniform variable.
  1044. * @param uniformName Name of the variable.
  1045. * @param value value to be set.
  1046. * @returns this effect.
  1047. */
  1048. Effect.prototype.setFloat = function (uniformName, value) {
  1049. var cache = this._valueCache[uniformName];
  1050. if (cache !== undefined && cache === value)
  1051. return this;
  1052. this._valueCache[uniformName] = value;
  1053. this._engine.setFloat(this.getUniform(uniformName), value);
  1054. return this;
  1055. };
  1056. /**
  1057. * Sets a boolean on a uniform variable.
  1058. * @param uniformName Name of the variable.
  1059. * @param bool value to be set.
  1060. * @returns this effect.
  1061. */
  1062. Effect.prototype.setBool = function (uniformName, bool) {
  1063. var cache = this._valueCache[uniformName];
  1064. if (cache !== undefined && cache === bool)
  1065. return this;
  1066. this._valueCache[uniformName] = bool;
  1067. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1068. return this;
  1069. };
  1070. /**
  1071. * Sets a Vector2 on a uniform variable.
  1072. * @param uniformName Name of the variable.
  1073. * @param vector2 vector2 to be set.
  1074. * @returns this effect.
  1075. */
  1076. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1077. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1078. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1079. }
  1080. return this;
  1081. };
  1082. /**
  1083. * Sets a float2 on a uniform variable.
  1084. * @param uniformName Name of the variable.
  1085. * @param x First float in float2.
  1086. * @param y Second float in float2.
  1087. * @returns this effect.
  1088. */
  1089. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1090. if (this._cacheFloat2(uniformName, x, y)) {
  1091. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1092. }
  1093. return this;
  1094. };
  1095. /**
  1096. * Sets a Vector3 on a uniform variable.
  1097. * @param uniformName Name of the variable.
  1098. * @param vector3 Value to be set.
  1099. * @returns this effect.
  1100. */
  1101. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1102. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1103. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1104. }
  1105. return this;
  1106. };
  1107. /**
  1108. * Sets a float3 on a uniform variable.
  1109. * @param uniformName Name of the variable.
  1110. * @param x First float in float3.
  1111. * @param y Second float in float3.
  1112. * @param z Third float in float3.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1116. if (this._cacheFloat3(uniformName, x, y, z)) {
  1117. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1118. }
  1119. return this;
  1120. };
  1121. /**
  1122. * Sets a Vector4 on a uniform variable.
  1123. * @param uniformName Name of the variable.
  1124. * @param vector4 Value to be set.
  1125. * @returns this effect.
  1126. */
  1127. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1128. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1129. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1130. }
  1131. return this;
  1132. };
  1133. /**
  1134. * Sets a float4 on a uniform variable.
  1135. * @param uniformName Name of the variable.
  1136. * @param x First float in float4.
  1137. * @param y Second float in float4.
  1138. * @param z Third float in float4.
  1139. * @param w Fourth float in float4.
  1140. * @returns this effect.
  1141. */
  1142. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1143. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1144. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1145. }
  1146. return this;
  1147. };
  1148. /**
  1149. * Sets a Color3 on a uniform variable.
  1150. * @param uniformName Name of the variable.
  1151. * @param color3 Value to be set.
  1152. * @returns this effect.
  1153. */
  1154. Effect.prototype.setColor3 = function (uniformName, color3) {
  1155. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1156. this._engine.setColor3(this.getUniform(uniformName), color3);
  1157. }
  1158. return this;
  1159. };
  1160. /**
  1161. * Sets a Color4 on a uniform variable.
  1162. * @param uniformName Name of the variable.
  1163. * @param color3 Value to be set.
  1164. * @param alpha Alpha value to be set.
  1165. * @returns this effect.
  1166. */
  1167. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1168. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1169. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1170. }
  1171. return this;
  1172. };
  1173. /**
  1174. * Sets a Color4 on a uniform variable
  1175. * @param uniformName defines the name of the variable
  1176. * @param color4 defines the value to be set
  1177. * @returns this effect.
  1178. */
  1179. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1180. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1181. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1182. }
  1183. return this;
  1184. };
  1185. /**
  1186. * Resets the cache of effects.
  1187. */
  1188. Effect.ResetCache = function () {
  1189. Effect._baseCache = {};
  1190. };
  1191. Effect._uniqueIdSeed = 0;
  1192. Effect._baseCache = {};
  1193. // Statics
  1194. /**
  1195. * Store of each shader (The can be looked up using effect.key)
  1196. */
  1197. Effect.ShadersStore = {};
  1198. /**
  1199. * Store of each included file for a shader (The can be looked up using effect.key)
  1200. */
  1201. Effect.IncludesShadersStore = {};
  1202. return Effect;
  1203. }());
  1204. BABYLON.Effect = Effect;
  1205. })(BABYLON || (BABYLON = {}));
  1206. //# sourceMappingURL=babylon.effect.js.map
  1207. //# sourceMappingURL=babylon.types.js.map
  1208. var BABYLON;
  1209. (function (BABYLON) {
  1210. var KeyboardEventTypes = /** @class */ (function () {
  1211. function KeyboardEventTypes() {
  1212. }
  1213. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1214. get: function () {
  1215. return KeyboardEventTypes._KEYDOWN;
  1216. },
  1217. enumerable: true,
  1218. configurable: true
  1219. });
  1220. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1221. get: function () {
  1222. return KeyboardEventTypes._KEYUP;
  1223. },
  1224. enumerable: true,
  1225. configurable: true
  1226. });
  1227. KeyboardEventTypes._KEYDOWN = 0x01;
  1228. KeyboardEventTypes._KEYUP = 0x02;
  1229. return KeyboardEventTypes;
  1230. }());
  1231. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1232. var KeyboardInfo = /** @class */ (function () {
  1233. function KeyboardInfo(type, event) {
  1234. this.type = type;
  1235. this.event = event;
  1236. }
  1237. return KeyboardInfo;
  1238. }());
  1239. BABYLON.KeyboardInfo = KeyboardInfo;
  1240. /**
  1241. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1242. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1243. */
  1244. var KeyboardInfoPre = /** @class */ (function (_super) {
  1245. __extends(KeyboardInfoPre, _super);
  1246. function KeyboardInfoPre(type, event) {
  1247. var _this = _super.call(this, type, event) || this;
  1248. _this.skipOnPointerObservable = false;
  1249. return _this;
  1250. }
  1251. return KeyboardInfoPre;
  1252. }(KeyboardInfo));
  1253. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1254. })(BABYLON || (BABYLON = {}));
  1255. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1256. var BABYLON;
  1257. (function (BABYLON) {
  1258. var PointerEventTypes = /** @class */ (function () {
  1259. function PointerEventTypes() {
  1260. }
  1261. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1262. get: function () {
  1263. return PointerEventTypes._POINTERDOWN;
  1264. },
  1265. enumerable: true,
  1266. configurable: true
  1267. });
  1268. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1269. get: function () {
  1270. return PointerEventTypes._POINTERUP;
  1271. },
  1272. enumerable: true,
  1273. configurable: true
  1274. });
  1275. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1276. get: function () {
  1277. return PointerEventTypes._POINTERMOVE;
  1278. },
  1279. enumerable: true,
  1280. configurable: true
  1281. });
  1282. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1283. get: function () {
  1284. return PointerEventTypes._POINTERWHEEL;
  1285. },
  1286. enumerable: true,
  1287. configurable: true
  1288. });
  1289. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1290. get: function () {
  1291. return PointerEventTypes._POINTERPICK;
  1292. },
  1293. enumerable: true,
  1294. configurable: true
  1295. });
  1296. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1297. get: function () {
  1298. return PointerEventTypes._POINTERTAP;
  1299. },
  1300. enumerable: true,
  1301. configurable: true
  1302. });
  1303. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1304. get: function () {
  1305. return PointerEventTypes._POINTERDOUBLETAP;
  1306. },
  1307. enumerable: true,
  1308. configurable: true
  1309. });
  1310. PointerEventTypes._POINTERDOWN = 0x01;
  1311. PointerEventTypes._POINTERUP = 0x02;
  1312. PointerEventTypes._POINTERMOVE = 0x04;
  1313. PointerEventTypes._POINTERWHEEL = 0x08;
  1314. PointerEventTypes._POINTERPICK = 0x10;
  1315. PointerEventTypes._POINTERTAP = 0x20;
  1316. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1317. return PointerEventTypes;
  1318. }());
  1319. BABYLON.PointerEventTypes = PointerEventTypes;
  1320. var PointerInfoBase = /** @class */ (function () {
  1321. function PointerInfoBase(type, event) {
  1322. this.type = type;
  1323. this.event = event;
  1324. }
  1325. return PointerInfoBase;
  1326. }());
  1327. BABYLON.PointerInfoBase = PointerInfoBase;
  1328. /**
  1329. * This class is used to store pointer related info for the onPrePointerObservable event.
  1330. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1331. */
  1332. var PointerInfoPre = /** @class */ (function (_super) {
  1333. __extends(PointerInfoPre, _super);
  1334. function PointerInfoPre(type, event, localX, localY) {
  1335. var _this = _super.call(this, type, event) || this;
  1336. _this.skipOnPointerObservable = false;
  1337. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1338. return _this;
  1339. }
  1340. return PointerInfoPre;
  1341. }(PointerInfoBase));
  1342. BABYLON.PointerInfoPre = PointerInfoPre;
  1343. /**
  1344. * This type contains all the data related to a pointer event in Babylon.js.
  1345. * 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.
  1346. */
  1347. var PointerInfo = /** @class */ (function (_super) {
  1348. __extends(PointerInfo, _super);
  1349. function PointerInfo(type, event, pickInfo) {
  1350. var _this = _super.call(this, type, event) || this;
  1351. _this.pickInfo = pickInfo;
  1352. return _this;
  1353. }
  1354. return PointerInfo;
  1355. }(PointerInfoBase));
  1356. BABYLON.PointerInfo = PointerInfo;
  1357. })(BABYLON || (BABYLON = {}));
  1358. //# sourceMappingURL=babylon.pointerEvents.js.map
  1359. var BABYLON;
  1360. (function (BABYLON) {
  1361. BABYLON.ToGammaSpace = 1 / 2.2;
  1362. BABYLON.ToLinearSpace = 2.2;
  1363. BABYLON.Epsilon = 0.001;
  1364. /**
  1365. * Class used to hold a RBG color
  1366. */
  1367. var Color3 = /** @class */ (function () {
  1368. /**
  1369. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1370. * @param r defines the red component (between 0 and 1, default is 0)
  1371. * @param g defines the green component (between 0 and 1, default is 0)
  1372. * @param b defines the blue component (between 0 and 1, default is 0)
  1373. */
  1374. function Color3(
  1375. /**
  1376. * Defines the red component (between 0 and 1, default is 0)
  1377. */
  1378. r,
  1379. /**
  1380. * Defines the green component (between 0 and 1, default is 0)
  1381. */
  1382. g,
  1383. /**
  1384. * Defines the blue component (between 0 and 1, default is 0)
  1385. */
  1386. b) {
  1387. if (r === void 0) { r = 0; }
  1388. if (g === void 0) { g = 0; }
  1389. if (b === void 0) { b = 0; }
  1390. this.r = r;
  1391. this.g = g;
  1392. this.b = b;
  1393. }
  1394. /**
  1395. * Creates a string with the Color3 current values
  1396. * @returns the string representation of the Color3 object
  1397. */
  1398. Color3.prototype.toString = function () {
  1399. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1400. };
  1401. /**
  1402. * Returns the string "Color3"
  1403. * @returns "Color3"
  1404. */
  1405. Color3.prototype.getClassName = function () {
  1406. return "Color3";
  1407. };
  1408. /**
  1409. * Compute the Color3 hash code
  1410. * @returns an unique number that can be used to hash Color3 objects
  1411. */
  1412. Color3.prototype.getHashCode = function () {
  1413. var hash = this.r || 0;
  1414. hash = (hash * 397) ^ (this.g || 0);
  1415. hash = (hash * 397) ^ (this.b || 0);
  1416. return hash;
  1417. };
  1418. // Operators
  1419. /**
  1420. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1421. * @param array defines the array where to store the r,g,b components
  1422. * @param index defines an optional index in the target array to define where to start storing values
  1423. * @returns the current Color3 object
  1424. */
  1425. Color3.prototype.toArray = function (array, index) {
  1426. if (index === undefined) {
  1427. index = 0;
  1428. }
  1429. array[index] = this.r;
  1430. array[index + 1] = this.g;
  1431. array[index + 2] = this.b;
  1432. return this;
  1433. };
  1434. /**
  1435. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1436. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1437. * @returns a new {BABYLON.Color4} object
  1438. */
  1439. Color3.prototype.toColor4 = function (alpha) {
  1440. if (alpha === void 0) { alpha = 1; }
  1441. return new Color4(this.r, this.g, this.b, alpha);
  1442. };
  1443. /**
  1444. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1445. * @returns the new array
  1446. */
  1447. Color3.prototype.asArray = function () {
  1448. var result = new Array();
  1449. this.toArray(result, 0);
  1450. return result;
  1451. };
  1452. /**
  1453. * Returns the luminance value
  1454. * @returns a float value
  1455. */
  1456. Color3.prototype.toLuminance = function () {
  1457. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1458. };
  1459. /**
  1460. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1461. * @param otherColor defines the second operand
  1462. * @returns the new Color3 object
  1463. */
  1464. Color3.prototype.multiply = function (otherColor) {
  1465. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1466. };
  1467. /**
  1468. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1469. * @param otherColor defines the second operand
  1470. * @param result defines the Color3 object where to store the result
  1471. * @returns the current Color3
  1472. */
  1473. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1474. result.r = this.r * otherColor.r;
  1475. result.g = this.g * otherColor.g;
  1476. result.b = this.b * otherColor.b;
  1477. return this;
  1478. };
  1479. /**
  1480. * Determines equality between Color3 objects
  1481. * @param otherColor defines the second operand
  1482. * @returns true if the rgb values are equal to the passed ones
  1483. */
  1484. Color3.prototype.equals = function (otherColor) {
  1485. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1486. };
  1487. /**
  1488. * Determines equality between the current Color3 object and a set of r,b,g values
  1489. * @param r defines the red component to check
  1490. * @param g defines the green component to check
  1491. * @param b defines the blue component to check
  1492. * @returns true if the rgb values are equal to the passed ones
  1493. */
  1494. Color3.prototype.equalsFloats = function (r, g, b) {
  1495. return this.r === r && this.g === g && this.b === b;
  1496. };
  1497. /**
  1498. * Multiplies in place each rgb value by scale
  1499. * @param scale defines the scaling factor
  1500. * @returns the updated Color3.
  1501. */
  1502. Color3.prototype.scale = function (scale) {
  1503. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1504. };
  1505. /**
  1506. * Multiplies the rgb values by scale and stores the result into "result"
  1507. * @param scale defines the scaling factor
  1508. * @param result defines the Color3 object where to store the result
  1509. * @returns the unmodified current Color3.
  1510. */
  1511. Color3.prototype.scaleToRef = function (scale, result) {
  1512. result.r = this.r * scale;
  1513. result.g = this.g * scale;
  1514. result.b = this.b * scale;
  1515. return this;
  1516. };
  1517. /**
  1518. * Clamps the rgb values by the min and max values and stores the result into "result"
  1519. * @param min defines minimum clamping value (default is 0)
  1520. * @param max defines maximum clamping value (default is 1)
  1521. * @param result defines color to store the result into
  1522. * @returns the original Color3
  1523. */
  1524. Color3.prototype.clampToRef = function (min, max, result) {
  1525. if (min === void 0) { min = 0; }
  1526. if (max === void 0) { max = 1; }
  1527. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1528. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1529. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1530. return this;
  1531. };
  1532. /**
  1533. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1534. * @param otherColor defines the second operand
  1535. * @returns the new Color3
  1536. */
  1537. Color3.prototype.add = function (otherColor) {
  1538. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1539. };
  1540. /**
  1541. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1542. * @param otherColor defines the second operand
  1543. * @param result defines Color3 object to store the result into
  1544. * @returns the unmodified current Color3
  1545. */
  1546. Color3.prototype.addToRef = function (otherColor, result) {
  1547. result.r = this.r + otherColor.r;
  1548. result.g = this.g + otherColor.g;
  1549. result.b = this.b + otherColor.b;
  1550. return this;
  1551. };
  1552. /**
  1553. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1554. * @param otherColor defines the second operand
  1555. * @returns the new Color3
  1556. */
  1557. Color3.prototype.subtract = function (otherColor) {
  1558. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1559. };
  1560. /**
  1561. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1562. * @param otherColor defines the second operand
  1563. * @param result defines Color3 object to store the result into
  1564. * @returns the unmodified current Color3
  1565. */
  1566. Color3.prototype.subtractToRef = function (otherColor, result) {
  1567. result.r = this.r - otherColor.r;
  1568. result.g = this.g - otherColor.g;
  1569. result.b = this.b - otherColor.b;
  1570. return this;
  1571. };
  1572. /**
  1573. * Copy the current object
  1574. * @returns a new Color3 copied the current one
  1575. */
  1576. Color3.prototype.clone = function () {
  1577. return new Color3(this.r, this.g, this.b);
  1578. };
  1579. /**
  1580. * Copies the rgb values from the source in the current Color3
  1581. * @param source defines the source Color3 object
  1582. * @returns the updated Color3 object
  1583. */
  1584. Color3.prototype.copyFrom = function (source) {
  1585. this.r = source.r;
  1586. this.g = source.g;
  1587. this.b = source.b;
  1588. return this;
  1589. };
  1590. /**
  1591. * Updates the Color3 rgb values from the passed floats
  1592. * @param r defines the red component to read from
  1593. * @param g defines the green component to read from
  1594. * @param b defines the blue component to read from
  1595. * @returns the current Color3 object
  1596. */
  1597. Color3.prototype.copyFromFloats = function (r, g, b) {
  1598. this.r = r;
  1599. this.g = g;
  1600. this.b = b;
  1601. return this;
  1602. };
  1603. /**
  1604. * Updates the Color3 rgb values from the passed floats
  1605. * @param r defines the red component to read from
  1606. * @param g defines the green component to read from
  1607. * @param b defines the blue component to read from
  1608. * @returns the current Color3 object
  1609. */
  1610. Color3.prototype.set = function (r, g, b) {
  1611. return this.copyFromFloats(r, g, b);
  1612. };
  1613. /**
  1614. * Compute the Color3 hexadecimal code as a string
  1615. * @returns a string containing the hexadecimal representation of the Color3 object
  1616. */
  1617. Color3.prototype.toHexString = function () {
  1618. var intR = (this.r * 255) | 0;
  1619. var intG = (this.g * 255) | 0;
  1620. var intB = (this.b * 255) | 0;
  1621. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1622. };
  1623. /**
  1624. * Computes a new Color3 converted from the current one to linear space
  1625. * @returns a new Color3 object
  1626. */
  1627. Color3.prototype.toLinearSpace = function () {
  1628. var convertedColor = new Color3();
  1629. this.toLinearSpaceToRef(convertedColor);
  1630. return convertedColor;
  1631. };
  1632. /**
  1633. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1634. * @param convertedColor defines the Color3 object where to store the linear space version
  1635. * @returns the unmodified Color3
  1636. */
  1637. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1638. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1639. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1640. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1641. return this;
  1642. };
  1643. /**
  1644. * Computes a new Color3 converted from the current one to gamma space
  1645. * @returns a new Color3 object
  1646. */
  1647. Color3.prototype.toGammaSpace = function () {
  1648. var convertedColor = new Color3();
  1649. this.toGammaSpaceToRef(convertedColor);
  1650. return convertedColor;
  1651. };
  1652. /**
  1653. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1654. * @param convertedColor defines the Color3 object where to store the gamma space version
  1655. * @returns the unmodified Color3
  1656. */
  1657. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1658. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1659. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1660. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1661. return this;
  1662. };
  1663. // Statics
  1664. /**
  1665. * Creates a new Color3 from the string containing valid hexadecimal values
  1666. * @param hex defines a string containing valid hexadecimal values
  1667. * @returns a new Color3 object
  1668. */
  1669. Color3.FromHexString = function (hex) {
  1670. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1671. return new Color3(0, 0, 0);
  1672. }
  1673. var r = parseInt(hex.substring(1, 3), 16);
  1674. var g = parseInt(hex.substring(3, 5), 16);
  1675. var b = parseInt(hex.substring(5, 7), 16);
  1676. return Color3.FromInts(r, g, b);
  1677. };
  1678. /**
  1679. * Creates a new Vector3 from the starting index of the passed array
  1680. * @param array defines the source array
  1681. * @param offset defines an offset in the source array
  1682. * @returns a new Color3 object
  1683. */
  1684. Color3.FromArray = function (array, offset) {
  1685. if (offset === void 0) { offset = 0; }
  1686. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1687. };
  1688. /**
  1689. * Creates a new Color3 from integer values (< 256)
  1690. * @param r defines the red component to read from (value between 0 and 255)
  1691. * @param g defines the green component to read from (value between 0 and 255)
  1692. * @param b defines the blue component to read from (value between 0 and 255)
  1693. * @returns a new Color3 object
  1694. */
  1695. Color3.FromInts = function (r, g, b) {
  1696. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1697. };
  1698. /**
  1699. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1700. * @param start defines the start Color3 value
  1701. * @param end defines the end Color3 value
  1702. * @param amount defines the gradient value between start and end
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.Lerp = function (start, end, amount) {
  1706. var r = start.r + ((end.r - start.r) * amount);
  1707. var g = start.g + ((end.g - start.g) * amount);
  1708. var b = start.b + ((end.b - start.b) * amount);
  1709. return new Color3(r, g, b);
  1710. };
  1711. /**
  1712. * Returns a Color3 value containing a red color
  1713. * @returns a new Color3 object
  1714. */
  1715. Color3.Red = function () { return new Color3(1, 0, 0); };
  1716. /**
  1717. * Returns a Color3 value containing a green color
  1718. * @returns a new Color3 object
  1719. */
  1720. Color3.Green = function () { return new Color3(0, 1, 0); };
  1721. /**
  1722. * Returns a Color3 value containing a blue color
  1723. * @returns a new Color3 object
  1724. */
  1725. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1726. /**
  1727. * Returns a Color3 value containing a black color
  1728. * @returns a new Color3 object
  1729. */
  1730. Color3.Black = function () { return new Color3(0, 0, 0); };
  1731. /**
  1732. * Returns a Color3 value containing a white color
  1733. * @returns a new Color3 object
  1734. */
  1735. Color3.White = function () { return new Color3(1, 1, 1); };
  1736. /**
  1737. * Returns a Color3 value containing a purple color
  1738. * @returns a new Color3 object
  1739. */
  1740. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1741. /**
  1742. * Returns a Color3 value containing a magenta color
  1743. * @returns a new Color3 object
  1744. */
  1745. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1746. /**
  1747. * Returns a Color3 value containing a yellow color
  1748. * @returns a new Color3 object
  1749. */
  1750. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1751. /**
  1752. * Returns a Color3 value containing a gray color
  1753. * @returns a new Color3 object
  1754. */
  1755. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1756. /**
  1757. * Returns a Color3 value containing a teal color
  1758. * @returns a new Color3 object
  1759. */
  1760. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1761. /**
  1762. * Returns a Color3 value containing a random color
  1763. * @returns a new Color3 object
  1764. */
  1765. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1766. return Color3;
  1767. }());
  1768. BABYLON.Color3 = Color3;
  1769. /**
  1770. * Class used to hold a RBGA color
  1771. */
  1772. var Color4 = /** @class */ (function () {
  1773. /**
  1774. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1775. * @param r defines the red component (between 0 and 1, default is 0)
  1776. * @param g defines the green component (between 0 and 1, default is 0)
  1777. * @param b defines the blue component (between 0 and 1, default is 0)
  1778. * @param a defines the alpha component (between 0 and 1, default is 1)
  1779. */
  1780. function Color4(
  1781. /**
  1782. * Defines the red component (between 0 and 1, default is 0)
  1783. */
  1784. r,
  1785. /**
  1786. * Defines the green component (between 0 and 1, default is 0)
  1787. */
  1788. g,
  1789. /**
  1790. * Defines the blue component (between 0 and 1, default is 0)
  1791. */
  1792. b,
  1793. /**
  1794. * Defines the alpha component (between 0 and 1, default is 1)
  1795. */
  1796. a) {
  1797. if (r === void 0) { r = 0; }
  1798. if (g === void 0) { g = 0; }
  1799. if (b === void 0) { b = 0; }
  1800. if (a === void 0) { a = 1; }
  1801. this.r = r;
  1802. this.g = g;
  1803. this.b = b;
  1804. this.a = a;
  1805. }
  1806. // Operators
  1807. /**
  1808. * Adds in place the passed Color4 values to the current Color4 object
  1809. * @param right defines the second operand
  1810. * @returns the current updated Color4 object
  1811. */
  1812. Color4.prototype.addInPlace = function (right) {
  1813. this.r += right.r;
  1814. this.g += right.g;
  1815. this.b += right.b;
  1816. this.a += right.a;
  1817. return this;
  1818. };
  1819. /**
  1820. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1821. * @returns the new array
  1822. */
  1823. Color4.prototype.asArray = function () {
  1824. var result = new Array();
  1825. this.toArray(result, 0);
  1826. return result;
  1827. };
  1828. /**
  1829. * Stores from the starting index in the passed array the Color4 successive values
  1830. * @param array defines the array where to store the r,g,b components
  1831. * @param index defines an optional index in the target array to define where to start storing values
  1832. * @returns the current Color4 object
  1833. */
  1834. Color4.prototype.toArray = function (array, index) {
  1835. if (index === undefined) {
  1836. index = 0;
  1837. }
  1838. array[index] = this.r;
  1839. array[index + 1] = this.g;
  1840. array[index + 2] = this.b;
  1841. array[index + 3] = this.a;
  1842. return this;
  1843. };
  1844. /**
  1845. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1846. * @param right defines the second operand
  1847. * @returns a new Color4 object
  1848. */
  1849. Color4.prototype.add = function (right) {
  1850. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1851. };
  1852. /**
  1853. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1854. * @param right defines the second operand
  1855. * @returns a new Color4 object
  1856. */
  1857. Color4.prototype.subtract = function (right) {
  1858. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1859. };
  1860. /**
  1861. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1862. * @param right defines the second operand
  1863. * @param result defines the Color4 object where to store the result
  1864. * @returns the current Color4 object
  1865. */
  1866. Color4.prototype.subtractToRef = function (right, result) {
  1867. result.r = this.r - right.r;
  1868. result.g = this.g - right.g;
  1869. result.b = this.b - right.b;
  1870. result.a = this.a - right.a;
  1871. return this;
  1872. };
  1873. /**
  1874. * Creates a new Color4 with the current Color4 values multiplied by scale
  1875. * @param scale defines the scaling factor to apply
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.scale = function (scale) {
  1879. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1880. };
  1881. /**
  1882. * Multiplies the current Color4 values by scale and stores the result in "result"
  1883. * @param scale defines the scaling factor to apply
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4.
  1886. */
  1887. Color4.prototype.scaleToRef = function (scale, result) {
  1888. result.r = this.r * scale;
  1889. result.g = this.g * scale;
  1890. result.b = this.b * scale;
  1891. result.a = this.a * scale;
  1892. return this;
  1893. };
  1894. /**
  1895. * Clamps the rgb values by the min and max values and stores the result into "result"
  1896. * @param min defines minimum clamping value (default is 0)
  1897. * @param max defines maximum clamping value (default is 1)
  1898. * @param result defines color to store the result into.
  1899. * @returns the cuurent Color4
  1900. */
  1901. Color4.prototype.clampToRef = function (min, max, result) {
  1902. if (min === void 0) { min = 0; }
  1903. if (max === void 0) { max = 1; }
  1904. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1905. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1906. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1907. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1908. return this;
  1909. };
  1910. /**
  1911. * Multipy an Color4 value by another and return a new Color4 object
  1912. * @param color defines the Color4 value to multiply by
  1913. * @returns a new Color4 object
  1914. */
  1915. Color4.prototype.multiply = function (color) {
  1916. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1917. };
  1918. /**
  1919. * Multipy a Color4 value by another and push the result in a reference value
  1920. * @param color defines the Color4 value to multiply by
  1921. * @param result defines the Color4 to fill the result in
  1922. * @returns the result Color4
  1923. */
  1924. Color4.prototype.multiplyToRef = function (color, result) {
  1925. result.r = this.r * color.r;
  1926. result.g = this.g * color.g;
  1927. result.b = this.b * color.b;
  1928. result.a = this.a * color.a;
  1929. return result;
  1930. };
  1931. /**
  1932. * Creates a string with the Color4 current values
  1933. * @returns the string representation of the Color4 object
  1934. */
  1935. Color4.prototype.toString = function () {
  1936. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1937. };
  1938. /**
  1939. * Returns the string "Color4"
  1940. * @returns "Color4"
  1941. */
  1942. Color4.prototype.getClassName = function () {
  1943. return "Color4";
  1944. };
  1945. /**
  1946. * Compute the Color4 hash code
  1947. * @returns an unique number that can be used to hash Color4 objects
  1948. */
  1949. Color4.prototype.getHashCode = function () {
  1950. var hash = this.r || 0;
  1951. hash = (hash * 397) ^ (this.g || 0);
  1952. hash = (hash * 397) ^ (this.b || 0);
  1953. hash = (hash * 397) ^ (this.a || 0);
  1954. return hash;
  1955. };
  1956. /**
  1957. * Creates a new Color4 copied from the current one
  1958. * @returns a new Color4 object
  1959. */
  1960. Color4.prototype.clone = function () {
  1961. return new Color4(this.r, this.g, this.b, this.a);
  1962. };
  1963. /**
  1964. * Copies the passed Color4 values into the current one
  1965. * @param source defines the source Color4 object
  1966. * @returns the current updated Color4 object
  1967. */
  1968. Color4.prototype.copyFrom = function (source) {
  1969. this.r = source.r;
  1970. this.g = source.g;
  1971. this.b = source.b;
  1972. this.a = source.a;
  1973. return this;
  1974. };
  1975. /**
  1976. * Copies the passed float values into the current one
  1977. * @param r defines the red component to read from
  1978. * @param g defines the green component to read from
  1979. * @param b defines the blue component to read from
  1980. * @param a defines the alpha component to read from
  1981. * @returns the current updated Color4 object
  1982. */
  1983. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1984. this.r = r;
  1985. this.g = g;
  1986. this.b = b;
  1987. this.a = a;
  1988. return this;
  1989. };
  1990. /**
  1991. * Copies the passed float values into the current one
  1992. * @param r defines the red component to read from
  1993. * @param g defines the green component to read from
  1994. * @param b defines the blue component to read from
  1995. * @param a defines the alpha component to read from
  1996. * @returns the current updated Color4 object
  1997. */
  1998. Color4.prototype.set = function (r, g, b, a) {
  1999. return this.copyFromFloats(r, g, b, a);
  2000. };
  2001. /**
  2002. * Compute the Color4 hexadecimal code as a string
  2003. * @returns a string containing the hexadecimal representation of the Color4 object
  2004. */
  2005. Color4.prototype.toHexString = function () {
  2006. var intR = (this.r * 255) | 0;
  2007. var intG = (this.g * 255) | 0;
  2008. var intB = (this.b * 255) | 0;
  2009. var intA = (this.a * 255) | 0;
  2010. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2011. };
  2012. /**
  2013. * Computes a new Color4 converted from the current one to linear space
  2014. * @returns a new Color4 object
  2015. */
  2016. Color4.prototype.toLinearSpace = function () {
  2017. var convertedColor = new Color4();
  2018. this.toLinearSpaceToRef(convertedColor);
  2019. return convertedColor;
  2020. };
  2021. /**
  2022. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2023. * @param convertedColor defines the Color4 object where to store the linear space version
  2024. * @returns the unmodified Color4
  2025. */
  2026. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2027. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2028. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2029. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2030. convertedColor.a = this.a;
  2031. return this;
  2032. };
  2033. /**
  2034. * Computes a new Color4 converted from the current one to gamma space
  2035. * @returns a new Color4 object
  2036. */
  2037. Color4.prototype.toGammaSpace = function () {
  2038. var convertedColor = new Color4();
  2039. this.toGammaSpaceToRef(convertedColor);
  2040. return convertedColor;
  2041. };
  2042. /**
  2043. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2044. * @param convertedColor defines the Color4 object where to store the gamma space version
  2045. * @returns the unmodified Color4
  2046. */
  2047. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2048. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2049. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2050. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2051. convertedColor.a = this.a;
  2052. return this;
  2053. };
  2054. // Statics
  2055. /**
  2056. * Creates a new Color4 from the string containing valid hexadecimal values
  2057. * @param hex defines a string containing valid hexadecimal values
  2058. * @returns a new Color4 object
  2059. */
  2060. Color4.FromHexString = function (hex) {
  2061. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2062. return new Color4(0.0, 0.0, 0.0, 0.0);
  2063. }
  2064. var r = parseInt(hex.substring(1, 3), 16);
  2065. var g = parseInt(hex.substring(3, 5), 16);
  2066. var b = parseInt(hex.substring(5, 7), 16);
  2067. var a = parseInt(hex.substring(7, 9), 16);
  2068. return Color4.FromInts(r, g, b, a);
  2069. };
  2070. /**
  2071. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2072. * @param left defines the start value
  2073. * @param right defines the end value
  2074. * @param amount defines the gradient factor
  2075. * @returns a new Color4 object
  2076. */
  2077. Color4.Lerp = function (left, right, amount) {
  2078. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2079. Color4.LerpToRef(left, right, amount, result);
  2080. return result;
  2081. };
  2082. /**
  2083. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2084. * @param left defines the start value
  2085. * @param right defines the end value
  2086. * @param amount defines the gradient factor
  2087. * @param result defines the Color4 object where to store data
  2088. */
  2089. Color4.LerpToRef = function (left, right, amount, result) {
  2090. result.r = left.r + (right.r - left.r) * amount;
  2091. result.g = left.g + (right.g - left.g) * amount;
  2092. result.b = left.b + (right.b - left.b) * amount;
  2093. result.a = left.a + (right.a - left.a) * amount;
  2094. };
  2095. /**
  2096. * Creates a new Color4 from the starting index element of the passed array
  2097. * @param array defines the source array to read from
  2098. * @param offset defines the offset in the source array
  2099. * @returns a new Color4 object
  2100. */
  2101. Color4.FromArray = function (array, offset) {
  2102. if (offset === void 0) { offset = 0; }
  2103. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2104. };
  2105. /**
  2106. * Creates a new Color3 from integer values (< 256)
  2107. * @param r defines the red component to read from (value between 0 and 255)
  2108. * @param g defines the green component to read from (value between 0 and 255)
  2109. * @param b defines the blue component to read from (value between 0 and 255)
  2110. * @param a defines the alpha component to read from (value between 0 and 255)
  2111. * @returns a new Color3 object
  2112. */
  2113. Color4.FromInts = function (r, g, b, a) {
  2114. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2115. };
  2116. /**
  2117. * Check the content of a given array and convert it to an array containing RGBA data
  2118. * If the original array was already containing count * 4 values then it is returned directly
  2119. * @param colors defines the array to check
  2120. * @param count defines the number of RGBA data to expect
  2121. * @returns an array containing count * 4 values (RGBA)
  2122. */
  2123. Color4.CheckColors4 = function (colors, count) {
  2124. // Check if color3 was used
  2125. if (colors.length === count * 3) {
  2126. var colors4 = [];
  2127. for (var index = 0; index < colors.length; index += 3) {
  2128. var newIndex = (index / 3) * 4;
  2129. colors4[newIndex] = colors[index];
  2130. colors4[newIndex + 1] = colors[index + 1];
  2131. colors4[newIndex + 2] = colors[index + 2];
  2132. colors4[newIndex + 3] = 1.0;
  2133. }
  2134. return colors4;
  2135. }
  2136. return colors;
  2137. };
  2138. return Color4;
  2139. }());
  2140. BABYLON.Color4 = Color4;
  2141. var Vector2 = /** @class */ (function () {
  2142. /**
  2143. * Creates a new Vector2 from the passed x and y coordinates.
  2144. */
  2145. function Vector2(x, y) {
  2146. this.x = x;
  2147. this.y = y;
  2148. }
  2149. /**
  2150. * Returns a string with the Vector2 coordinates.
  2151. */
  2152. Vector2.prototype.toString = function () {
  2153. return "{X: " + this.x + " Y:" + this.y + "}";
  2154. };
  2155. /**
  2156. * Returns the string "Vector2"
  2157. */
  2158. Vector2.prototype.getClassName = function () {
  2159. return "Vector2";
  2160. };
  2161. /**
  2162. * Returns the Vector2 hash code as a number.
  2163. */
  2164. Vector2.prototype.getHashCode = function () {
  2165. var hash = this.x || 0;
  2166. hash = (hash * 397) ^ (this.y || 0);
  2167. return hash;
  2168. };
  2169. // Operators
  2170. /**
  2171. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2172. * Returns the Vector2.
  2173. */
  2174. Vector2.prototype.toArray = function (array, index) {
  2175. if (index === void 0) { index = 0; }
  2176. array[index] = this.x;
  2177. array[index + 1] = this.y;
  2178. return this;
  2179. };
  2180. /**
  2181. * Returns a new array with 2 elements : the Vector2 coordinates.
  2182. */
  2183. Vector2.prototype.asArray = function () {
  2184. var result = new Array();
  2185. this.toArray(result, 0);
  2186. return result;
  2187. };
  2188. /**
  2189. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2190. * Returns the updated Vector2.
  2191. */
  2192. Vector2.prototype.copyFrom = function (source) {
  2193. this.x = source.x;
  2194. this.y = source.y;
  2195. return this;
  2196. };
  2197. /**
  2198. * Sets the Vector2 coordinates with the passed floats.
  2199. * Returns the updated Vector2.
  2200. */
  2201. Vector2.prototype.copyFromFloats = function (x, y) {
  2202. this.x = x;
  2203. this.y = y;
  2204. return this;
  2205. };
  2206. /**
  2207. * Sets the Vector2 coordinates with the passed floats.
  2208. * Returns the updated Vector2.
  2209. */
  2210. Vector2.prototype.set = function (x, y) {
  2211. return this.copyFromFloats(x, y);
  2212. };
  2213. /**
  2214. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2215. */
  2216. Vector2.prototype.add = function (otherVector) {
  2217. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2218. };
  2219. /**
  2220. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2221. * Returns the Vector2.
  2222. */
  2223. Vector2.prototype.addToRef = function (otherVector, result) {
  2224. result.x = this.x + otherVector.x;
  2225. result.y = this.y + otherVector.y;
  2226. return this;
  2227. };
  2228. /**
  2229. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2230. * Returns the updated Vector2.
  2231. */
  2232. Vector2.prototype.addInPlace = function (otherVector) {
  2233. this.x += otherVector.x;
  2234. this.y += otherVector.y;
  2235. return this;
  2236. };
  2237. /**
  2238. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2239. */
  2240. Vector2.prototype.addVector3 = function (otherVector) {
  2241. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2242. };
  2243. /**
  2244. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2245. */
  2246. Vector2.prototype.subtract = function (otherVector) {
  2247. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2248. };
  2249. /**
  2250. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2251. * Returns the Vector2.
  2252. */
  2253. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2254. result.x = this.x - otherVector.x;
  2255. result.y = this.y - otherVector.y;
  2256. return this;
  2257. };
  2258. /**
  2259. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2260. * Returns the updated Vector2.
  2261. */
  2262. Vector2.prototype.subtractInPlace = function (otherVector) {
  2263. this.x -= otherVector.x;
  2264. this.y -= otherVector.y;
  2265. return this;
  2266. };
  2267. /**
  2268. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2269. * Returns the updated Vector2.
  2270. */
  2271. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2272. this.x *= otherVector.x;
  2273. this.y *= otherVector.y;
  2274. return this;
  2275. };
  2276. /**
  2277. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2278. */
  2279. Vector2.prototype.multiply = function (otherVector) {
  2280. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2281. };
  2282. /**
  2283. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2284. * Returns the Vector2.
  2285. */
  2286. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2287. result.x = this.x * otherVector.x;
  2288. result.y = this.y * otherVector.y;
  2289. return this;
  2290. };
  2291. /**
  2292. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2293. */
  2294. Vector2.prototype.multiplyByFloats = function (x, y) {
  2295. return new Vector2(this.x * x, this.y * y);
  2296. };
  2297. /**
  2298. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2299. */
  2300. Vector2.prototype.divide = function (otherVector) {
  2301. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2302. };
  2303. /**
  2304. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2305. * Returns the Vector2.
  2306. */
  2307. Vector2.prototype.divideToRef = function (otherVector, result) {
  2308. result.x = this.x / otherVector.x;
  2309. result.y = this.y / otherVector.y;
  2310. return this;
  2311. };
  2312. /**
  2313. * Divides the current Vector3 coordinates by the passed ones.
  2314. * Returns the updated Vector3.
  2315. */
  2316. Vector2.prototype.divideInPlace = function (otherVector) {
  2317. return this.divideToRef(otherVector, this);
  2318. };
  2319. /**
  2320. * Returns a new Vector2 with current Vector2 negated coordinates.
  2321. */
  2322. Vector2.prototype.negate = function () {
  2323. return new Vector2(-this.x, -this.y);
  2324. };
  2325. /**
  2326. * Multiply the Vector2 coordinates by scale.
  2327. * Returns the updated Vector2.
  2328. */
  2329. Vector2.prototype.scaleInPlace = function (scale) {
  2330. this.x *= scale;
  2331. this.y *= scale;
  2332. return this;
  2333. };
  2334. /**
  2335. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2336. */
  2337. Vector2.prototype.scale = function (scale) {
  2338. return new Vector2(this.x * scale, this.y * scale);
  2339. };
  2340. /**
  2341. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2342. */
  2343. Vector2.prototype.equals = function (otherVector) {
  2344. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2345. };
  2346. /**
  2347. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2348. */
  2349. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2350. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2351. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2352. };
  2353. // Properties
  2354. /**
  2355. * Returns the vector length (float).
  2356. */
  2357. Vector2.prototype.length = function () {
  2358. return Math.sqrt(this.x * this.x + this.y * this.y);
  2359. };
  2360. /**
  2361. * Returns the vector squared length (float);
  2362. */
  2363. Vector2.prototype.lengthSquared = function () {
  2364. return (this.x * this.x + this.y * this.y);
  2365. };
  2366. // Methods
  2367. /**
  2368. * Normalize the vector.
  2369. * Returns the updated Vector2.
  2370. */
  2371. Vector2.prototype.normalize = function () {
  2372. var len = this.length();
  2373. if (len === 0)
  2374. return this;
  2375. var num = 1.0 / len;
  2376. this.x *= num;
  2377. this.y *= num;
  2378. return this;
  2379. };
  2380. /**
  2381. * Returns a new Vector2 copied from the Vector2.
  2382. */
  2383. Vector2.prototype.clone = function () {
  2384. return new Vector2(this.x, this.y);
  2385. };
  2386. // Statics
  2387. /**
  2388. * Returns a new Vector2(0, 0)
  2389. */
  2390. Vector2.Zero = function () {
  2391. return new Vector2(0, 0);
  2392. };
  2393. /**
  2394. * Returns a new Vector2(1, 1)
  2395. */
  2396. Vector2.One = function () {
  2397. return new Vector2(1, 1);
  2398. };
  2399. /**
  2400. * Returns a new Vector2 set from the passed index element of the passed array.
  2401. */
  2402. Vector2.FromArray = function (array, offset) {
  2403. if (offset === void 0) { offset = 0; }
  2404. return new Vector2(array[offset], array[offset + 1]);
  2405. };
  2406. /**
  2407. * Sets "result" from the passed index element of the passed array.
  2408. */
  2409. Vector2.FromArrayToRef = function (array, offset, result) {
  2410. result.x = array[offset];
  2411. result.y = array[offset + 1];
  2412. };
  2413. /**
  2414. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2415. */
  2416. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2417. var squared = amount * amount;
  2418. var cubed = amount * squared;
  2419. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2420. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2421. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2422. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2423. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2424. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2425. return new Vector2(x, y);
  2426. };
  2427. /**
  2428. * 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".
  2429. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2430. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2431. */
  2432. Vector2.Clamp = function (value, min, max) {
  2433. var x = value.x;
  2434. x = (x > max.x) ? max.x : x;
  2435. x = (x < min.x) ? min.x : x;
  2436. var y = value.y;
  2437. y = (y > max.y) ? max.y : y;
  2438. y = (y < min.y) ? min.y : y;
  2439. return new Vector2(x, y);
  2440. };
  2441. /**
  2442. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2443. */
  2444. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2445. var squared = amount * amount;
  2446. var cubed = amount * squared;
  2447. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2448. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2449. var part3 = (cubed - (2.0 * squared)) + amount;
  2450. var part4 = cubed - squared;
  2451. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2452. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2453. return new Vector2(x, y);
  2454. };
  2455. /**
  2456. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2457. */
  2458. Vector2.Lerp = function (start, end, amount) {
  2459. var x = start.x + ((end.x - start.x) * amount);
  2460. var y = start.y + ((end.y - start.y) * amount);
  2461. return new Vector2(x, y);
  2462. };
  2463. /**
  2464. * Returns the dot product (float) of the vector "left" and the vector "right".
  2465. */
  2466. Vector2.Dot = function (left, right) {
  2467. return left.x * right.x + left.y * right.y;
  2468. };
  2469. /**
  2470. * Returns a new Vector2 equal to the normalized passed vector.
  2471. */
  2472. Vector2.Normalize = function (vector) {
  2473. var newVector = vector.clone();
  2474. newVector.normalize();
  2475. return newVector;
  2476. };
  2477. /**
  2478. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2479. */
  2480. Vector2.Minimize = function (left, right) {
  2481. var x = (left.x < right.x) ? left.x : right.x;
  2482. var y = (left.y < right.y) ? left.y : right.y;
  2483. return new Vector2(x, y);
  2484. };
  2485. /**
  2486. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2487. */
  2488. Vector2.Maximize = function (left, right) {
  2489. var x = (left.x > right.x) ? left.x : right.x;
  2490. var y = (left.y > right.y) ? left.y : right.y;
  2491. return new Vector2(x, y);
  2492. };
  2493. /**
  2494. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2495. */
  2496. Vector2.Transform = function (vector, transformation) {
  2497. var r = Vector2.Zero();
  2498. Vector2.TransformToRef(vector, transformation, r);
  2499. return r;
  2500. };
  2501. /**
  2502. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2503. */
  2504. Vector2.TransformToRef = function (vector, transformation, result) {
  2505. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2506. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2507. result.x = x;
  2508. result.y = y;
  2509. };
  2510. /**
  2511. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2512. */
  2513. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2514. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2515. var sign = a < 0 ? -1 : 1;
  2516. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2517. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2518. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2519. };
  2520. /**
  2521. * Returns the distance (float) between the vectors "value1" and "value2".
  2522. */
  2523. Vector2.Distance = function (value1, value2) {
  2524. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2525. };
  2526. /**
  2527. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2528. */
  2529. Vector2.DistanceSquared = function (value1, value2) {
  2530. var x = value1.x - value2.x;
  2531. var y = value1.y - value2.y;
  2532. return (x * x) + (y * y);
  2533. };
  2534. /**
  2535. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2536. */
  2537. Vector2.Center = function (value1, value2) {
  2538. var center = value1.add(value2);
  2539. center.scaleInPlace(0.5);
  2540. return center;
  2541. };
  2542. /**
  2543. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2544. */
  2545. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2546. var l2 = Vector2.DistanceSquared(segA, segB);
  2547. if (l2 === 0.0) {
  2548. return Vector2.Distance(p, segA);
  2549. }
  2550. var v = segB.subtract(segA);
  2551. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2552. var proj = segA.add(v.multiplyByFloats(t, t));
  2553. return Vector2.Distance(p, proj);
  2554. };
  2555. return Vector2;
  2556. }());
  2557. BABYLON.Vector2 = Vector2;
  2558. /**
  2559. * Classed used to store (x,y,z) vector representation
  2560. * A Vector3 is the main object used in 3D geometry
  2561. * It can represent etiher the coordinates of a point the space, either a direction
  2562. * Reminder: Babylon.js uses a left handed forward facing system
  2563. */
  2564. var Vector3 = /** @class */ (function () {
  2565. /**
  2566. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2567. * @param x defines the first coordinates (on X axis)
  2568. * @param y defines the second coordinates (on Y axis)
  2569. * @param z defines the third coordinates (on Z axis)
  2570. */
  2571. function Vector3(
  2572. /**
  2573. * Defines the first coordinates (on X axis)
  2574. */
  2575. x,
  2576. /**
  2577. * Defines the second coordinates (on Y axis)
  2578. */
  2579. y,
  2580. /**
  2581. * Defines the third coordinates (on Z axis)
  2582. */
  2583. z) {
  2584. this.x = x;
  2585. this.y = y;
  2586. this.z = z;
  2587. }
  2588. /**
  2589. * Creates a string representation of the Vector3
  2590. * @returns a string with the Vector3 coordinates.
  2591. */
  2592. Vector3.prototype.toString = function () {
  2593. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2594. };
  2595. /**
  2596. * Gets the class name
  2597. * @returns the string "Vector3"
  2598. */
  2599. Vector3.prototype.getClassName = function () {
  2600. return "Vector3";
  2601. };
  2602. /**
  2603. * Creates the Vector3 hash code
  2604. * @returns a number which tends to be unique between Vector3 instances
  2605. */
  2606. Vector3.prototype.getHashCode = function () {
  2607. var hash = this.x || 0;
  2608. hash = (hash * 397) ^ (this.y || 0);
  2609. hash = (hash * 397) ^ (this.z || 0);
  2610. return hash;
  2611. };
  2612. // Operators
  2613. /**
  2614. * Creates an array containing three elements : the coordinates of the Vector3
  2615. * @returns a new array of numbers
  2616. */
  2617. Vector3.prototype.asArray = function () {
  2618. var result = [];
  2619. this.toArray(result, 0);
  2620. return result;
  2621. };
  2622. /**
  2623. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2624. * @param array defines the destination array
  2625. * @param index defines the offset in the destination array
  2626. * @returns the current Vector3
  2627. */
  2628. Vector3.prototype.toArray = function (array, index) {
  2629. if (index === void 0) { index = 0; }
  2630. array[index] = this.x;
  2631. array[index + 1] = this.y;
  2632. array[index + 2] = this.z;
  2633. return this;
  2634. };
  2635. /**
  2636. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2637. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2638. */
  2639. Vector3.prototype.toQuaternion = function () {
  2640. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2641. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2642. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2643. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2644. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2645. var cosy = Math.cos(this.y * 0.5);
  2646. var siny = Math.sin(this.y * 0.5);
  2647. result.x = coszMinusx * siny;
  2648. result.y = -sinzMinusx * siny;
  2649. result.z = sinxPlusz * cosy;
  2650. result.w = cosxPlusz * cosy;
  2651. return result;
  2652. };
  2653. /**
  2654. * Adds the passed vector to the current Vector3
  2655. * @param otherVector defines the second operand
  2656. * @returns the current updated Vector3
  2657. */
  2658. Vector3.prototype.addInPlace = function (otherVector) {
  2659. this.x += otherVector.x;
  2660. this.y += otherVector.y;
  2661. this.z += otherVector.z;
  2662. return this;
  2663. };
  2664. /**
  2665. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2666. * @param otherVector defines the second operand
  2667. * @returns the resulting Vector3
  2668. */
  2669. Vector3.prototype.add = function (otherVector) {
  2670. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2671. };
  2672. /**
  2673. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2674. * @param otherVector defines the second operand
  2675. * @param result defines the Vector3 object where to store the result
  2676. * @returns the current Vector3
  2677. */
  2678. Vector3.prototype.addToRef = function (otherVector, result) {
  2679. result.x = this.x + otherVector.x;
  2680. result.y = this.y + otherVector.y;
  2681. result.z = this.z + otherVector.z;
  2682. return this;
  2683. };
  2684. /**
  2685. * Subtract the passed vector from the current Vector3
  2686. * @param otherVector defines the second operand
  2687. * @returns the current updated Vector3
  2688. */
  2689. Vector3.prototype.subtractInPlace = function (otherVector) {
  2690. this.x -= otherVector.x;
  2691. this.y -= otherVector.y;
  2692. this.z -= otherVector.z;
  2693. return this;
  2694. };
  2695. /**
  2696. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2697. * @param otherVector defines the second operand
  2698. * @returns the resulting Vector3
  2699. */
  2700. Vector3.prototype.subtract = function (otherVector) {
  2701. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2702. };
  2703. /**
  2704. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2705. * @param otherVector defines the second operand
  2706. * @param result defines the Vector3 object where to store the result
  2707. * @returns the current Vector3
  2708. */
  2709. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2710. result.x = this.x - otherVector.x;
  2711. result.y = this.y - otherVector.y;
  2712. result.z = this.z - otherVector.z;
  2713. return this;
  2714. };
  2715. /**
  2716. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2717. * @param x defines the x coordinate of the operand
  2718. * @param y defines the y coordinate of the operand
  2719. * @param z defines the z coordinate of the operand
  2720. * @returns the resulting Vector3
  2721. */
  2722. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2723. return new Vector3(this.x - x, this.y - y, this.z - z);
  2724. };
  2725. /**
  2726. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2727. * @param x defines the x coordinate of the operand
  2728. * @param y defines the y coordinate of the operand
  2729. * @param z defines the z coordinate of the operand
  2730. * @param result defines the Vector3 object where to store the result
  2731. * @returns the current Vector3
  2732. */
  2733. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2734. result.x = this.x - x;
  2735. result.y = this.y - y;
  2736. result.z = this.z - z;
  2737. return this;
  2738. };
  2739. /**
  2740. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2741. * @returns a new Vector3
  2742. */
  2743. Vector3.prototype.negate = function () {
  2744. return new Vector3(-this.x, -this.y, -this.z);
  2745. };
  2746. /**
  2747. * Multiplies the Vector3 coordinates by the float "scale"
  2748. * @param scale defines the multiplier factor
  2749. * @returns the current updated Vector3
  2750. */
  2751. Vector3.prototype.scaleInPlace = function (scale) {
  2752. this.x *= scale;
  2753. this.y *= scale;
  2754. this.z *= scale;
  2755. return this;
  2756. };
  2757. /**
  2758. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2759. * @param scale defines the multiplier factor
  2760. * @returns a new Vector3
  2761. */
  2762. Vector3.prototype.scale = function (scale) {
  2763. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2764. };
  2765. /**
  2766. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2767. * @param scale defines the multiplier factor
  2768. * @param result defines the Vector3 object where to store the result
  2769. * @returns the current Vector3
  2770. */
  2771. Vector3.prototype.scaleToRef = function (scale, result) {
  2772. result.x = this.x * scale;
  2773. result.y = this.y * scale;
  2774. result.z = this.z * scale;
  2775. return this;
  2776. };
  2777. /**
  2778. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2779. * @param otherVector defines the second operand
  2780. * @returns true if both vectors are equals
  2781. */
  2782. Vector3.prototype.equals = function (otherVector) {
  2783. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2784. };
  2785. /**
  2786. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2787. * @param otherVector defines the second operand
  2788. * @param epsilon defines the minimal distance to define values as equals
  2789. * @returns true if both vectors are distant less than epsilon
  2790. */
  2791. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2792. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2793. 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);
  2794. };
  2795. /**
  2796. * Returns true if the current Vector3 coordinates equals the passed floats
  2797. * @param x defines the x coordinate of the operand
  2798. * @param y defines the y coordinate of the operand
  2799. * @param z defines the z coordinate of the operand
  2800. * @returns true if both vectors are equals
  2801. */
  2802. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2803. return this.x === x && this.y === y && this.z === z;
  2804. };
  2805. /**
  2806. * Multiplies the current Vector3 coordinates by the passed ones
  2807. * @param otherVector defines the second operand
  2808. * @returns the current updated Vector3
  2809. */
  2810. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2811. this.x *= otherVector.x;
  2812. this.y *= otherVector.y;
  2813. this.z *= otherVector.z;
  2814. return this;
  2815. };
  2816. /**
  2817. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2818. * @param otherVector defines the second operand
  2819. * @returns the new Vector3
  2820. */
  2821. Vector3.prototype.multiply = function (otherVector) {
  2822. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2823. };
  2824. /**
  2825. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2826. * @param otherVector defines the second operand
  2827. * @param result defines the Vector3 object where to store the result
  2828. * @returns the current Vector3
  2829. */
  2830. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2831. result.x = this.x * otherVector.x;
  2832. result.y = this.y * otherVector.y;
  2833. result.z = this.z * otherVector.z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2838. * @param x defines the x coordinate of the operand
  2839. * @param y defines the y coordinate of the operand
  2840. * @param z defines the z coordinate of the operand
  2841. * @returns the new Vector3
  2842. */
  2843. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2844. return new Vector3(this.x * x, this.y * y, this.z * z);
  2845. };
  2846. /**
  2847. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2848. * @param otherVector defines the second operand
  2849. * @returns the new Vector3
  2850. */
  2851. Vector3.prototype.divide = function (otherVector) {
  2852. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2853. };
  2854. /**
  2855. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2856. * @param otherVector defines the second operand
  2857. * @param result defines the Vector3 object where to store the result
  2858. * @returns the current Vector3
  2859. */
  2860. Vector3.prototype.divideToRef = function (otherVector, result) {
  2861. result.x = this.x / otherVector.x;
  2862. result.y = this.y / otherVector.y;
  2863. result.z = this.z / otherVector.z;
  2864. return this;
  2865. };
  2866. /**
  2867. * Divides the current Vector3 coordinates by the passed ones.
  2868. * @param otherVector defines the second operand
  2869. * @returns the current updated Vector3
  2870. */
  2871. Vector3.prototype.divideInPlace = function (otherVector) {
  2872. return this.divideToRef(otherVector, this);
  2873. };
  2874. /**
  2875. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2876. * @param other defines the second operand
  2877. * @returns the current updated Vector3
  2878. */
  2879. Vector3.prototype.minimizeInPlace = function (other) {
  2880. if (other.x < this.x)
  2881. this.x = other.x;
  2882. if (other.y < this.y)
  2883. this.y = other.y;
  2884. if (other.z < this.z)
  2885. this.z = other.z;
  2886. return this;
  2887. };
  2888. /**
  2889. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2890. * @param other defines the second operand
  2891. * @returns the current updated Vector3
  2892. */
  2893. Vector3.prototype.maximizeInPlace = function (other) {
  2894. if (other.x > this.x)
  2895. this.x = other.x;
  2896. if (other.y > this.y)
  2897. this.y = other.y;
  2898. if (other.z > this.z)
  2899. this.z = other.z;
  2900. return this;
  2901. };
  2902. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2903. /**
  2904. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2905. */
  2906. get: function () {
  2907. var absX = Math.abs(this.x);
  2908. var absY = Math.abs(this.y);
  2909. if (absX !== absY) {
  2910. return true;
  2911. }
  2912. var absZ = Math.abs(this.z);
  2913. if (absX !== absZ) {
  2914. return true;
  2915. }
  2916. if (absY !== absZ) {
  2917. return true;
  2918. }
  2919. return false;
  2920. },
  2921. enumerable: true,
  2922. configurable: true
  2923. });
  2924. // Properties
  2925. /**
  2926. * Gets the length of the Vector3
  2927. * @returns the length of the Vecto3
  2928. */
  2929. Vector3.prototype.length = function () {
  2930. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2931. };
  2932. /**
  2933. * Gets the squared length of the Vector3
  2934. * @returns squared length of the Vector3
  2935. */
  2936. Vector3.prototype.lengthSquared = function () {
  2937. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2938. };
  2939. /**
  2940. * Normalize the current Vector3.
  2941. * Please note that this is an in place operation.
  2942. * @returns the current updated Vector3
  2943. */
  2944. Vector3.prototype.normalize = function () {
  2945. var len = this.length();
  2946. if (len === 0 || len === 1.0)
  2947. return this;
  2948. var num = 1.0 / len;
  2949. this.x *= num;
  2950. this.y *= num;
  2951. this.z *= num;
  2952. return this;
  2953. };
  2954. /**
  2955. * Normalize the current Vector3 to a new vector
  2956. * @returns the new Vector3
  2957. */
  2958. Vector3.prototype.normalizeToNew = function () {
  2959. var normalized = new Vector3(0, 0, 0);
  2960. this.normalizeToRef(normalized);
  2961. return normalized;
  2962. };
  2963. /**
  2964. * Normalize the current Vector3 to the reference
  2965. * @param reference define the Vector3 to update
  2966. * @returns the updated Vector3
  2967. */
  2968. Vector3.prototype.normalizeToRef = function (reference) {
  2969. var len = this.length();
  2970. if (len === 0 || len === 1.0) {
  2971. reference.set(this.x, this.y, this.z);
  2972. return reference;
  2973. }
  2974. var scale = 1.0 / len;
  2975. this.scaleToRef(scale, reference);
  2976. return reference;
  2977. };
  2978. /**
  2979. * Creates a new Vector3 copied from the current Vector3
  2980. * @returns the new Vector3
  2981. */
  2982. Vector3.prototype.clone = function () {
  2983. return new Vector3(this.x, this.y, this.z);
  2984. };
  2985. /**
  2986. * Copies the passed vector coordinates to the current Vector3 ones
  2987. * @param source defines the source Vector3
  2988. * @returns the current updated Vector3
  2989. */
  2990. Vector3.prototype.copyFrom = function (source) {
  2991. this.x = source.x;
  2992. this.y = source.y;
  2993. this.z = source.z;
  2994. return this;
  2995. };
  2996. /**
  2997. * Copies the passed floats to the current Vector3 coordinates
  2998. * @param x defines the x coordinate of the operand
  2999. * @param y defines the y coordinate of the operand
  3000. * @param z defines the z coordinate of the operand
  3001. * @returns the current updated Vector3
  3002. */
  3003. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3004. this.x = x;
  3005. this.y = y;
  3006. this.z = z;
  3007. return this;
  3008. };
  3009. /**
  3010. * Copies the passed floats to the current Vector3 coordinates
  3011. * @param x defines the x coordinate of the operand
  3012. * @param y defines the y coordinate of the operand
  3013. * @param z defines the z coordinate of the operand
  3014. * @returns the current updated Vector3
  3015. */
  3016. Vector3.prototype.set = function (x, y, z) {
  3017. return this.copyFromFloats(x, y, z);
  3018. };
  3019. // Statics
  3020. /**
  3021. * Get the clip factor between two vectors
  3022. * @param vector0 defines the first operand
  3023. * @param vector1 defines the second operand
  3024. * @param axis defines the axis to use
  3025. * @param size defines the size along the axis
  3026. * @returns the clip factor
  3027. */
  3028. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3029. var d0 = Vector3.Dot(vector0, axis) - size;
  3030. var d1 = Vector3.Dot(vector1, axis) - size;
  3031. var s = d0 / (d0 - d1);
  3032. return s;
  3033. };
  3034. /**
  3035. * Get angle between two vectors
  3036. * @param vector0 angle between vector0 and vector1
  3037. * @param vector1 angle between vector0 and vector1
  3038. * @param normal direction of the normal
  3039. * @return the angle between vector0 and vector1
  3040. */
  3041. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3042. var v0 = vector0.clone().normalize();
  3043. var v1 = vector1.clone().normalize();
  3044. var dot = Vector3.Dot(v0, v1);
  3045. var n = Vector3.Cross(v0, v1);
  3046. if (Vector3.Dot(n, normal) > 0) {
  3047. return Math.acos(dot);
  3048. }
  3049. return -Math.acos(dot);
  3050. };
  3051. /**
  3052. * Returns a new Vector3 set from the index "offset" of the passed array
  3053. * @param array defines the source array
  3054. * @param offset defines the offset in the source array
  3055. * @returns the new Vector3
  3056. */
  3057. Vector3.FromArray = function (array, offset) {
  3058. if (!offset) {
  3059. offset = 0;
  3060. }
  3061. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3062. };
  3063. /**
  3064. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3065. * This function is deprecated. Use FromArray instead
  3066. * @param array defines the source array
  3067. * @param offset defines the offset in the source array
  3068. * @returns the new Vector3
  3069. */
  3070. Vector3.FromFloatArray = function (array, offset) {
  3071. return Vector3.FromArray(array, offset);
  3072. };
  3073. /**
  3074. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3075. * @param array defines the source array
  3076. * @param offset defines the offset in the source array
  3077. * @param result defines the Vector3 where to store the result
  3078. */
  3079. Vector3.FromArrayToRef = function (array, offset, result) {
  3080. result.x = array[offset];
  3081. result.y = array[offset + 1];
  3082. result.z = array[offset + 2];
  3083. };
  3084. /**
  3085. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3086. * This function is deprecated. Use FromArrayToRef instead.
  3087. * @param array defines the source array
  3088. * @param offset defines the offset in the source array
  3089. * @param result defines the Vector3 where to store the result
  3090. */
  3091. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3092. return Vector3.FromArrayToRef(array, offset, result);
  3093. };
  3094. /**
  3095. * Sets the passed vector "result" with the passed floats.
  3096. * @param x defines the x coordinate of the source
  3097. * @param y defines the y coordinate of the source
  3098. * @param z defines the z coordinate of the source
  3099. * @param result defines the Vector3 where to store the result
  3100. */
  3101. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3102. result.x = x;
  3103. result.y = y;
  3104. result.z = z;
  3105. };
  3106. /**
  3107. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3108. * @returns a new empty Vector3
  3109. */
  3110. Vector3.Zero = function () {
  3111. return new Vector3(0.0, 0.0, 0.0);
  3112. };
  3113. /**
  3114. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3115. * @returns a new unit Vector3
  3116. */
  3117. Vector3.One = function () {
  3118. return new Vector3(1.0, 1.0, 1.0);
  3119. };
  3120. /**
  3121. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3122. * @returns a new up Vector3
  3123. */
  3124. Vector3.Up = function () {
  3125. return new Vector3(0.0, 1.0, 0.0);
  3126. };
  3127. /**
  3128. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3129. * @returns a new forward Vector3
  3130. */
  3131. Vector3.Forward = function () {
  3132. return new Vector3(0.0, 0.0, 1.0);
  3133. };
  3134. /**
  3135. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3136. * @returns a new right Vector3
  3137. */
  3138. Vector3.Right = function () {
  3139. return new Vector3(1.0, 0.0, 0.0);
  3140. };
  3141. /**
  3142. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3143. * @returns a new left Vector3
  3144. */
  3145. Vector3.Left = function () {
  3146. return new Vector3(-1.0, 0.0, 0.0);
  3147. };
  3148. /**
  3149. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3150. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3151. * @param vector defines the Vector3 to transform
  3152. * @param transformation defines the transformation matrix
  3153. * @returns the transformed Vector3
  3154. */
  3155. Vector3.TransformCoordinates = function (vector, transformation) {
  3156. var result = Vector3.Zero();
  3157. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3158. return result;
  3159. };
  3160. /**
  3161. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3162. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3163. * @param vector defines the Vector3 to transform
  3164. * @param transformation defines the transformation matrix
  3165. * @param result defines the Vector3 where to store the result
  3166. */
  3167. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3168. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3169. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3170. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3171. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3172. result.x = x / w;
  3173. result.y = y / w;
  3174. result.z = z / w;
  3175. };
  3176. /**
  3177. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3178. * This method computes tranformed coordinates only, not transformed direction vectors
  3179. * @param x define the x coordinate of the source vector
  3180. * @param y define the y coordinate of the source vector
  3181. * @param z define the z coordinate of the source vector
  3182. * @param transformation defines the transformation matrix
  3183. * @param result defines the Vector3 where to store the result
  3184. */
  3185. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3186. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3187. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3188. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3189. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3190. result.x = rx / rw;
  3191. result.y = ry / rw;
  3192. result.z = rz / rw;
  3193. };
  3194. /**
  3195. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3196. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3197. * @param vector defines the Vector3 to transform
  3198. * @param transformation defines the transformation matrix
  3199. * @returns the new Vector3
  3200. */
  3201. Vector3.TransformNormal = function (vector, transformation) {
  3202. var result = Vector3.Zero();
  3203. Vector3.TransformNormalToRef(vector, transformation, result);
  3204. return result;
  3205. };
  3206. /**
  3207. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3208. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3209. * @param vector defines the Vector3 to transform
  3210. * @param transformation defines the transformation matrix
  3211. * @param result defines the Vector3 where to store the result
  3212. */
  3213. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3214. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3215. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3216. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3217. result.x = x;
  3218. result.y = y;
  3219. result.z = z;
  3220. };
  3221. /**
  3222. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3223. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3224. * @param x define the x coordinate of the source vector
  3225. * @param y define the y coordinate of the source vector
  3226. * @param z define the z coordinate of the source vector
  3227. * @param transformation defines the transformation matrix
  3228. * @param result defines the Vector3 where to store the result
  3229. */
  3230. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3231. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3232. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3233. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3234. };
  3235. /**
  3236. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3237. * @param value1 defines the first control point
  3238. * @param value2 defines the second control point
  3239. * @param value3 defines the third control point
  3240. * @param value4 defines the fourth control point
  3241. * @param amount defines the amount on the spline to use
  3242. * @returns the new Vector3
  3243. */
  3244. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3245. var squared = amount * amount;
  3246. var cubed = amount * squared;
  3247. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3248. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3249. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3250. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3251. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3252. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3253. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3254. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3255. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3256. return new Vector3(x, y, z);
  3257. };
  3258. /**
  3259. * 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"
  3260. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3261. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3262. * @param value defines the current value
  3263. * @param min defines the lower range value
  3264. * @param max defines the upper range value
  3265. * @returns the new Vector3
  3266. */
  3267. Vector3.Clamp = function (value, min, max) {
  3268. var x = value.x;
  3269. x = (x > max.x) ? max.x : x;
  3270. x = (x < min.x) ? min.x : x;
  3271. var y = value.y;
  3272. y = (y > max.y) ? max.y : y;
  3273. y = (y < min.y) ? min.y : y;
  3274. var z = value.z;
  3275. z = (z > max.z) ? max.z : z;
  3276. z = (z < min.z) ? min.z : z;
  3277. return new Vector3(x, y, z);
  3278. };
  3279. /**
  3280. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3281. * @param value1 defines the first control point
  3282. * @param tangent1 defines the first tangent vector
  3283. * @param value2 defines the second control point
  3284. * @param tangent2 defines the second tangent vector
  3285. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3286. * @returns the new Vector3
  3287. */
  3288. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3289. var squared = amount * amount;
  3290. var cubed = amount * squared;
  3291. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3292. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3293. var part3 = (cubed - (2.0 * squared)) + amount;
  3294. var part4 = cubed - squared;
  3295. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3296. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3297. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3298. return new Vector3(x, y, z);
  3299. };
  3300. /**
  3301. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3302. * @param start defines the start value
  3303. * @param end defines the end value
  3304. * @param amount max defines amount between both (between 0 and 1)
  3305. * @returns the new Vector3
  3306. */
  3307. Vector3.Lerp = function (start, end, amount) {
  3308. var result = new Vector3(0, 0, 0);
  3309. Vector3.LerpToRef(start, end, amount, result);
  3310. return result;
  3311. };
  3312. /**
  3313. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3314. * @param start defines the start value
  3315. * @param end defines the end value
  3316. * @param amount max defines amount between both (between 0 and 1)
  3317. * @param result defines the Vector3 where to store the result
  3318. */
  3319. Vector3.LerpToRef = function (start, end, amount, result) {
  3320. result.x = start.x + ((end.x - start.x) * amount);
  3321. result.y = start.y + ((end.y - start.y) * amount);
  3322. result.z = start.z + ((end.z - start.z) * amount);
  3323. };
  3324. /**
  3325. * Returns the dot product (float) between the vectors "left" and "right"
  3326. * @param left defines the left operand
  3327. * @param right defines the right operand
  3328. * @returns the dot product
  3329. */
  3330. Vector3.Dot = function (left, right) {
  3331. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3332. };
  3333. /**
  3334. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3335. * The cross product is then orthogonal to both "left" and "right"
  3336. * @param left defines the left operand
  3337. * @param right defines the right operand
  3338. * @returns the cross product
  3339. */
  3340. Vector3.Cross = function (left, right) {
  3341. var result = Vector3.Zero();
  3342. Vector3.CrossToRef(left, right, result);
  3343. return result;
  3344. };
  3345. /**
  3346. * Sets the passed vector "result" with the cross product of "left" and "right"
  3347. * The cross product is then orthogonal to both "left" and "right"
  3348. * @param left defines the left operand
  3349. * @param right defines the right operand
  3350. * @param result defines the Vector3 where to store the result
  3351. */
  3352. Vector3.CrossToRef = function (left, right, result) {
  3353. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3354. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3355. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3356. result.copyFrom(MathTmp.Vector3[0]);
  3357. };
  3358. /**
  3359. * Returns a new Vector3 as the normalization of the passed vector
  3360. * @param vector defines the Vector3 to normalize
  3361. * @returns the new Vector3
  3362. */
  3363. Vector3.Normalize = function (vector) {
  3364. var result = Vector3.Zero();
  3365. Vector3.NormalizeToRef(vector, result);
  3366. return result;
  3367. };
  3368. /**
  3369. * Sets the passed vector "result" with the normalization of the passed first vector
  3370. * @param vector defines the Vector3 to normalize
  3371. * @param result defines the Vector3 where to store the result
  3372. */
  3373. Vector3.NormalizeToRef = function (vector, result) {
  3374. result.copyFrom(vector);
  3375. result.normalize();
  3376. };
  3377. /**
  3378. * Project a Vector3 onto screen space
  3379. * @param vector defines the Vector3 to project
  3380. * @param world defines the world matrix to use
  3381. * @param transform defines the transform (view x projection) matrix to use
  3382. * @param viewport defines the screen viewport to use
  3383. * @returns the new Vector3
  3384. */
  3385. Vector3.Project = function (vector, world, transform, viewport) {
  3386. var cw = viewport.width;
  3387. var ch = viewport.height;
  3388. var cx = viewport.x;
  3389. var cy = viewport.y;
  3390. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3391. 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);
  3392. var matrix = MathTmp.Matrix[0];
  3393. world.multiplyToRef(transform, matrix);
  3394. matrix.multiplyToRef(viewportMatrix, matrix);
  3395. return Vector3.TransformCoordinates(vector, matrix);
  3396. };
  3397. /**
  3398. * Unproject from screen space to object space
  3399. * @param source defines the screen space Vector3 to use
  3400. * @param viewportWidth defines the current width of the viewport
  3401. * @param viewportHeight defines the current height of the viewport
  3402. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3403. * @param transform defines the transform (view x projection) matrix to use
  3404. * @returns the new Vector3
  3405. */
  3406. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3407. var matrix = MathTmp.Matrix[0];
  3408. world.multiplyToRef(transform, matrix);
  3409. matrix.invert();
  3410. source.x = source.x / viewportWidth * 2 - 1;
  3411. source.y = -(source.y / viewportHeight * 2 - 1);
  3412. var vector = Vector3.TransformCoordinates(source, matrix);
  3413. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3414. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3415. vector = vector.scale(1.0 / num);
  3416. }
  3417. return vector;
  3418. };
  3419. /**
  3420. * Unproject from screen space to object space
  3421. * @param source defines the screen space Vector3 to use
  3422. * @param viewportWidth defines the current width of the viewport
  3423. * @param viewportHeight defines the current height of the viewport
  3424. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3425. * @param view defines the view matrix to use
  3426. * @param projection defines the projection matrix to use
  3427. * @returns the new Vector3
  3428. */
  3429. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3430. var result = Vector3.Zero();
  3431. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3432. return result;
  3433. };
  3434. /**
  3435. * Unproject from screen space to object space
  3436. * @param source defines the screen space Vector3 to use
  3437. * @param viewportWidth defines the current width of the viewport
  3438. * @param viewportHeight defines the current height of the viewport
  3439. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3440. * @param view defines the view matrix to use
  3441. * @param projection defines the projection matrix to use
  3442. * @param result defines the Vector3 where to store the result
  3443. */
  3444. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3445. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3446. };
  3447. /**
  3448. * Unproject from screen space to object space
  3449. * @param sourceX defines the screen space x coordinate to use
  3450. * @param sourceY defines the screen space y coordinate to use
  3451. * @param sourceZ defines the screen space z coordinate to use
  3452. * @param viewportWidth defines the current width of the viewport
  3453. * @param viewportHeight defines the current height of the viewport
  3454. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3455. * @param view defines the view matrix to use
  3456. * @param projection defines the projection matrix to use
  3457. * @param result defines the Vector3 where to store the result
  3458. */
  3459. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3460. var matrix = MathTmp.Matrix[0];
  3461. world.multiplyToRef(view, matrix);
  3462. matrix.multiplyToRef(projection, matrix);
  3463. matrix.invert();
  3464. var screenSource = MathTmp.Vector3[0];
  3465. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3466. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3467. screenSource.z = 2 * sourceZ - 1.0;
  3468. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3469. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3470. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3471. result.scaleInPlace(1.0 / num);
  3472. }
  3473. };
  3474. /**
  3475. * Gets the minimal coordinate values between two Vector3
  3476. * @param left defines the first operand
  3477. * @param right defines the second operand
  3478. * @returns the new Vector3
  3479. */
  3480. Vector3.Minimize = function (left, right) {
  3481. var min = left.clone();
  3482. min.minimizeInPlace(right);
  3483. return min;
  3484. };
  3485. /**
  3486. * Gets the maximal coordinate values between two Vector3
  3487. * @param left defines the first operand
  3488. * @param right defines the second operand
  3489. * @returns the new Vector3
  3490. */
  3491. Vector3.Maximize = function (left, right) {
  3492. var max = left.clone();
  3493. max.maximizeInPlace(right);
  3494. return max;
  3495. };
  3496. /**
  3497. * Returns the distance between the vectors "value1" and "value2"
  3498. * @param value1 defines the first operand
  3499. * @param value2 defines the second operand
  3500. * @returns the distance
  3501. */
  3502. Vector3.Distance = function (value1, value2) {
  3503. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3504. };
  3505. /**
  3506. * Returns the squared distance between the vectors "value1" and "value2"
  3507. * @param value1 defines the first operand
  3508. * @param value2 defines the second operand
  3509. * @returns the squared distance
  3510. */
  3511. Vector3.DistanceSquared = function (value1, value2) {
  3512. var x = value1.x - value2.x;
  3513. var y = value1.y - value2.y;
  3514. var z = value1.z - value2.z;
  3515. return (x * x) + (y * y) + (z * z);
  3516. };
  3517. /**
  3518. * Returns a new Vector3 located at the center between "value1" and "value2"
  3519. * @param value1 defines the first operand
  3520. * @param value2 defines the second operand
  3521. * @returns the new Vector3
  3522. */
  3523. Vector3.Center = function (value1, value2) {
  3524. var center = value1.add(value2);
  3525. center.scaleInPlace(0.5);
  3526. return center;
  3527. };
  3528. /**
  3529. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3530. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3531. * to something in order to rotate it from its local system to the given target system
  3532. * Note: axis1, axis2 and axis3 are normalized during this operation
  3533. * @param axis1 defines the first axis
  3534. * @param axis2 defines the second axis
  3535. * @param axis3 defines the third axis
  3536. * @returns a new Vector3
  3537. */
  3538. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3539. var rotation = Vector3.Zero();
  3540. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3541. return rotation;
  3542. };
  3543. /**
  3544. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3545. * @param axis1 defines the first axis
  3546. * @param axis2 defines the second axis
  3547. * @param axis3 defines the third axis
  3548. * @param ref defines the Vector3 where to store the result
  3549. */
  3550. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3551. var quat = MathTmp.Quaternion[0];
  3552. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3553. quat.toEulerAnglesToRef(ref);
  3554. };
  3555. return Vector3;
  3556. }());
  3557. BABYLON.Vector3 = Vector3;
  3558. //Vector4 class created for EulerAngle class conversion to Quaternion
  3559. var Vector4 = /** @class */ (function () {
  3560. /**
  3561. * Creates a Vector4 object from the passed floats.
  3562. */
  3563. function Vector4(x, y, z, w) {
  3564. this.x = x;
  3565. this.y = y;
  3566. this.z = z;
  3567. this.w = w;
  3568. }
  3569. /**
  3570. * Returns the string with the Vector4 coordinates.
  3571. */
  3572. Vector4.prototype.toString = function () {
  3573. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3574. };
  3575. /**
  3576. * Returns the string "Vector4".
  3577. */
  3578. Vector4.prototype.getClassName = function () {
  3579. return "Vector4";
  3580. };
  3581. /**
  3582. * Returns the Vector4 hash code.
  3583. */
  3584. Vector4.prototype.getHashCode = function () {
  3585. var hash = this.x || 0;
  3586. hash = (hash * 397) ^ (this.y || 0);
  3587. hash = (hash * 397) ^ (this.z || 0);
  3588. hash = (hash * 397) ^ (this.w || 0);
  3589. return hash;
  3590. };
  3591. // Operators
  3592. /**
  3593. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3594. */
  3595. Vector4.prototype.asArray = function () {
  3596. var result = new Array();
  3597. this.toArray(result, 0);
  3598. return result;
  3599. };
  3600. /**
  3601. * Populates the passed array from the passed index with the Vector4 coordinates.
  3602. * Returns the Vector4.
  3603. */
  3604. Vector4.prototype.toArray = function (array, index) {
  3605. if (index === undefined) {
  3606. index = 0;
  3607. }
  3608. array[index] = this.x;
  3609. array[index + 1] = this.y;
  3610. array[index + 2] = this.z;
  3611. array[index + 3] = this.w;
  3612. return this;
  3613. };
  3614. /**
  3615. * Adds the passed vector to the current Vector4.
  3616. * Returns the updated Vector4.
  3617. */
  3618. Vector4.prototype.addInPlace = function (otherVector) {
  3619. this.x += otherVector.x;
  3620. this.y += otherVector.y;
  3621. this.z += otherVector.z;
  3622. this.w += otherVector.w;
  3623. return this;
  3624. };
  3625. /**
  3626. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3627. */
  3628. Vector4.prototype.add = function (otherVector) {
  3629. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3630. };
  3631. /**
  3632. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3633. * Returns the current Vector4.
  3634. */
  3635. Vector4.prototype.addToRef = function (otherVector, result) {
  3636. result.x = this.x + otherVector.x;
  3637. result.y = this.y + otherVector.y;
  3638. result.z = this.z + otherVector.z;
  3639. result.w = this.w + otherVector.w;
  3640. return this;
  3641. };
  3642. /**
  3643. * Subtract in place the passed vector from the current Vector4.
  3644. * Returns the updated Vector4.
  3645. */
  3646. Vector4.prototype.subtractInPlace = function (otherVector) {
  3647. this.x -= otherVector.x;
  3648. this.y -= otherVector.y;
  3649. this.z -= otherVector.z;
  3650. this.w -= otherVector.w;
  3651. return this;
  3652. };
  3653. /**
  3654. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3655. */
  3656. Vector4.prototype.subtract = function (otherVector) {
  3657. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3658. };
  3659. /**
  3660. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3661. * Returns the current Vector4.
  3662. */
  3663. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3664. result.x = this.x - otherVector.x;
  3665. result.y = this.y - otherVector.y;
  3666. result.z = this.z - otherVector.z;
  3667. result.w = this.w - otherVector.w;
  3668. return this;
  3669. };
  3670. /**
  3671. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3672. */
  3673. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3674. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3675. };
  3676. /**
  3677. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3678. * Returns the current Vector4.
  3679. */
  3680. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3681. result.x = this.x - x;
  3682. result.y = this.y - y;
  3683. result.z = this.z - z;
  3684. result.w = this.w - w;
  3685. return this;
  3686. };
  3687. /**
  3688. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3689. */
  3690. Vector4.prototype.negate = function () {
  3691. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3692. };
  3693. /**
  3694. * Multiplies the current Vector4 coordinates by scale (float).
  3695. * Returns the updated Vector4.
  3696. */
  3697. Vector4.prototype.scaleInPlace = function (scale) {
  3698. this.x *= scale;
  3699. this.y *= scale;
  3700. this.z *= scale;
  3701. this.w *= scale;
  3702. return this;
  3703. };
  3704. /**
  3705. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3706. */
  3707. Vector4.prototype.scale = function (scale) {
  3708. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3709. };
  3710. /**
  3711. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3712. * Returns the current Vector4.
  3713. */
  3714. Vector4.prototype.scaleToRef = function (scale, result) {
  3715. result.x = this.x * scale;
  3716. result.y = this.y * scale;
  3717. result.z = this.z * scale;
  3718. result.w = this.w * scale;
  3719. return this;
  3720. };
  3721. /**
  3722. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3723. */
  3724. Vector4.prototype.equals = function (otherVector) {
  3725. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3726. };
  3727. /**
  3728. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3729. */
  3730. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3731. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3732. return otherVector
  3733. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3734. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3735. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3736. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3737. };
  3738. /**
  3739. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3740. */
  3741. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3742. return this.x === x && this.y === y && this.z === z && this.w === w;
  3743. };
  3744. /**
  3745. * Multiplies in place the current Vector4 by the passed one.
  3746. * Returns the updated Vector4.
  3747. */
  3748. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3749. this.x *= otherVector.x;
  3750. this.y *= otherVector.y;
  3751. this.z *= otherVector.z;
  3752. this.w *= otherVector.w;
  3753. return this;
  3754. };
  3755. /**
  3756. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3757. */
  3758. Vector4.prototype.multiply = function (otherVector) {
  3759. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3760. };
  3761. /**
  3762. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3763. * Returns the current Vector4.
  3764. */
  3765. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3766. result.x = this.x * otherVector.x;
  3767. result.y = this.y * otherVector.y;
  3768. result.z = this.z * otherVector.z;
  3769. result.w = this.w * otherVector.w;
  3770. return this;
  3771. };
  3772. /**
  3773. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3774. */
  3775. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3776. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3777. };
  3778. /**
  3779. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3780. */
  3781. Vector4.prototype.divide = function (otherVector) {
  3782. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3783. };
  3784. /**
  3785. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3786. * Returns the current Vector4.
  3787. */
  3788. Vector4.prototype.divideToRef = function (otherVector, result) {
  3789. result.x = this.x / otherVector.x;
  3790. result.y = this.y / otherVector.y;
  3791. result.z = this.z / otherVector.z;
  3792. result.w = this.w / otherVector.w;
  3793. return this;
  3794. };
  3795. /**
  3796. * Divides the current Vector3 coordinates by the passed ones.
  3797. * @returns the updated Vector3.
  3798. */
  3799. Vector4.prototype.divideInPlace = function (otherVector) {
  3800. return this.divideToRef(otherVector, this);
  3801. };
  3802. /**
  3803. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3804. * @param other defines the second operand
  3805. * @returns the current updated Vector4
  3806. */
  3807. Vector4.prototype.minimizeInPlace = function (other) {
  3808. if (other.x < this.x)
  3809. this.x = other.x;
  3810. if (other.y < this.y)
  3811. this.y = other.y;
  3812. if (other.z < this.z)
  3813. this.z = other.z;
  3814. if (other.w < this.w)
  3815. this.w = other.w;
  3816. return this;
  3817. };
  3818. /**
  3819. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3820. * @param other defines the second operand
  3821. * @returns the current updated Vector4
  3822. */
  3823. Vector4.prototype.maximizeInPlace = function (other) {
  3824. if (other.x > this.x)
  3825. this.x = other.x;
  3826. if (other.y > this.y)
  3827. this.y = other.y;
  3828. if (other.z > this.z)
  3829. this.z = other.z;
  3830. if (other.w > this.w)
  3831. this.w = other.w;
  3832. return this;
  3833. };
  3834. // Properties
  3835. /**
  3836. * Returns the Vector4 length (float).
  3837. */
  3838. Vector4.prototype.length = function () {
  3839. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3840. };
  3841. /**
  3842. * Returns the Vector4 squared length (float).
  3843. */
  3844. Vector4.prototype.lengthSquared = function () {
  3845. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3846. };
  3847. // Methods
  3848. /**
  3849. * Normalizes in place the Vector4.
  3850. * Returns the updated Vector4.
  3851. */
  3852. Vector4.prototype.normalize = function () {
  3853. var len = this.length();
  3854. if (len === 0)
  3855. return this;
  3856. var num = 1.0 / len;
  3857. this.x *= num;
  3858. this.y *= num;
  3859. this.z *= num;
  3860. this.w *= num;
  3861. return this;
  3862. };
  3863. /**
  3864. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3865. */
  3866. Vector4.prototype.toVector3 = function () {
  3867. return new Vector3(this.x, this.y, this.z);
  3868. };
  3869. /**
  3870. * Returns a new Vector4 copied from the current one.
  3871. */
  3872. Vector4.prototype.clone = function () {
  3873. return new Vector4(this.x, this.y, this.z, this.w);
  3874. };
  3875. /**
  3876. * Updates the current Vector4 with the passed one coordinates.
  3877. * Returns the updated Vector4.
  3878. */
  3879. Vector4.prototype.copyFrom = function (source) {
  3880. this.x = source.x;
  3881. this.y = source.y;
  3882. this.z = source.z;
  3883. this.w = source.w;
  3884. return this;
  3885. };
  3886. /**
  3887. * Updates the current Vector4 coordinates with the passed floats.
  3888. * Returns the updated Vector4.
  3889. */
  3890. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3891. this.x = x;
  3892. this.y = y;
  3893. this.z = z;
  3894. this.w = w;
  3895. return this;
  3896. };
  3897. /**
  3898. * Updates the current Vector4 coordinates with the passed floats.
  3899. * Returns the updated Vector4.
  3900. */
  3901. Vector4.prototype.set = function (x, y, z, w) {
  3902. return this.copyFromFloats(x, y, z, w);
  3903. };
  3904. // Statics
  3905. /**
  3906. * Returns a new Vector4 set from the starting index of the passed array.
  3907. */
  3908. Vector4.FromArray = function (array, offset) {
  3909. if (!offset) {
  3910. offset = 0;
  3911. }
  3912. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3913. };
  3914. /**
  3915. * Updates the passed vector "result" from the starting index of the passed array.
  3916. */
  3917. Vector4.FromArrayToRef = function (array, offset, result) {
  3918. result.x = array[offset];
  3919. result.y = array[offset + 1];
  3920. result.z = array[offset + 2];
  3921. result.w = array[offset + 3];
  3922. };
  3923. /**
  3924. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3925. */
  3926. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3927. Vector4.FromArrayToRef(array, offset, result);
  3928. };
  3929. /**
  3930. * Updates the passed vector "result" coordinates from the passed floats.
  3931. */
  3932. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3933. result.x = x;
  3934. result.y = y;
  3935. result.z = z;
  3936. result.w = w;
  3937. };
  3938. /**
  3939. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3940. */
  3941. Vector4.Zero = function () {
  3942. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3943. };
  3944. /**
  3945. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3946. */
  3947. Vector4.One = function () {
  3948. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3949. };
  3950. /**
  3951. * Returns a new normalized Vector4 from the passed one.
  3952. */
  3953. Vector4.Normalize = function (vector) {
  3954. var result = Vector4.Zero();
  3955. Vector4.NormalizeToRef(vector, result);
  3956. return result;
  3957. };
  3958. /**
  3959. * Updates the passed vector "result" from the normalization of the passed one.
  3960. */
  3961. Vector4.NormalizeToRef = function (vector, result) {
  3962. result.copyFrom(vector);
  3963. result.normalize();
  3964. };
  3965. Vector4.Minimize = function (left, right) {
  3966. var min = left.clone();
  3967. min.minimizeInPlace(right);
  3968. return min;
  3969. };
  3970. Vector4.Maximize = function (left, right) {
  3971. var max = left.clone();
  3972. max.maximizeInPlace(right);
  3973. return max;
  3974. };
  3975. /**
  3976. * Returns the distance (float) between the vectors "value1" and "value2".
  3977. */
  3978. Vector4.Distance = function (value1, value2) {
  3979. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3980. };
  3981. /**
  3982. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3983. */
  3984. Vector4.DistanceSquared = function (value1, value2) {
  3985. var x = value1.x - value2.x;
  3986. var y = value1.y - value2.y;
  3987. var z = value1.z - value2.z;
  3988. var w = value1.w - value2.w;
  3989. return (x * x) + (y * y) + (z * z) + (w * w);
  3990. };
  3991. /**
  3992. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3993. */
  3994. Vector4.Center = function (value1, value2) {
  3995. var center = value1.add(value2);
  3996. center.scaleInPlace(0.5);
  3997. return center;
  3998. };
  3999. /**
  4000. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4001. * This methods computes transformed normalized direction vectors only.
  4002. */
  4003. Vector4.TransformNormal = function (vector, transformation) {
  4004. var result = Vector4.Zero();
  4005. Vector4.TransformNormalToRef(vector, transformation, result);
  4006. return result;
  4007. };
  4008. /**
  4009. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4010. * This methods computes transformed normalized direction vectors only.
  4011. */
  4012. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4013. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4014. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4015. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4016. result.x = x;
  4017. result.y = y;
  4018. result.z = z;
  4019. result.w = vector.w;
  4020. };
  4021. /**
  4022. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4023. * This methods computes transformed normalized direction vectors only.
  4024. */
  4025. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4026. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4027. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4028. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4029. result.w = w;
  4030. };
  4031. return Vector4;
  4032. }());
  4033. BABYLON.Vector4 = Vector4;
  4034. var Size = /** @class */ (function () {
  4035. /**
  4036. * Creates a Size object from the passed width and height (floats).
  4037. */
  4038. function Size(width, height) {
  4039. this.width = width;
  4040. this.height = height;
  4041. }
  4042. // Returns a string with the Size width and height.
  4043. Size.prototype.toString = function () {
  4044. return "{W: " + this.width + ", H: " + this.height + "}";
  4045. };
  4046. /**
  4047. * Returns the string "Size"
  4048. */
  4049. Size.prototype.getClassName = function () {
  4050. return "Size";
  4051. };
  4052. /**
  4053. * Returns the Size hash code.
  4054. */
  4055. Size.prototype.getHashCode = function () {
  4056. var hash = this.width || 0;
  4057. hash = (hash * 397) ^ (this.height || 0);
  4058. return hash;
  4059. };
  4060. /**
  4061. * Updates the current size from the passed one.
  4062. * Returns the updated Size.
  4063. */
  4064. Size.prototype.copyFrom = function (src) {
  4065. this.width = src.width;
  4066. this.height = src.height;
  4067. };
  4068. /**
  4069. * Updates in place the current Size from the passed floats.
  4070. * Returns the updated Size.
  4071. */
  4072. Size.prototype.copyFromFloats = function (width, height) {
  4073. this.width = width;
  4074. this.height = height;
  4075. return this;
  4076. };
  4077. /**
  4078. * Updates in place the current Size from the passed floats.
  4079. * Returns the updated Size.
  4080. */
  4081. Size.prototype.set = function (width, height) {
  4082. return this.copyFromFloats(width, height);
  4083. };
  4084. /**
  4085. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4086. */
  4087. Size.prototype.multiplyByFloats = function (w, h) {
  4088. return new Size(this.width * w, this.height * h);
  4089. };
  4090. /**
  4091. * Returns a new Size copied from the passed one.
  4092. */
  4093. Size.prototype.clone = function () {
  4094. return new Size(this.width, this.height);
  4095. };
  4096. /**
  4097. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4098. */
  4099. Size.prototype.equals = function (other) {
  4100. if (!other) {
  4101. return false;
  4102. }
  4103. return (this.width === other.width) && (this.height === other.height);
  4104. };
  4105. Object.defineProperty(Size.prototype, "surface", {
  4106. /**
  4107. * Returns the surface of the Size : width * height (float).
  4108. */
  4109. get: function () {
  4110. return this.width * this.height;
  4111. },
  4112. enumerable: true,
  4113. configurable: true
  4114. });
  4115. /**
  4116. * Returns a new Size set to (0.0, 0.0)
  4117. */
  4118. Size.Zero = function () {
  4119. return new Size(0.0, 0.0);
  4120. };
  4121. /**
  4122. * Returns a new Size set as the addition result of the current Size and the passed one.
  4123. */
  4124. Size.prototype.add = function (otherSize) {
  4125. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4126. return r;
  4127. };
  4128. /**
  4129. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4130. */
  4131. Size.prototype.subtract = function (otherSize) {
  4132. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4133. return r;
  4134. };
  4135. /**
  4136. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4137. */
  4138. Size.Lerp = function (start, end, amount) {
  4139. var w = start.width + ((end.width - start.width) * amount);
  4140. var h = start.height + ((end.height - start.height) * amount);
  4141. return new Size(w, h);
  4142. };
  4143. return Size;
  4144. }());
  4145. BABYLON.Size = Size;
  4146. var Quaternion = /** @class */ (function () {
  4147. /**
  4148. * Creates a new Quaternion from the passed floats.
  4149. */
  4150. function Quaternion(x, y, z, w) {
  4151. if (x === void 0) { x = 0.0; }
  4152. if (y === void 0) { y = 0.0; }
  4153. if (z === void 0) { z = 0.0; }
  4154. if (w === void 0) { w = 1.0; }
  4155. this.x = x;
  4156. this.y = y;
  4157. this.z = z;
  4158. this.w = w;
  4159. }
  4160. /**
  4161. * Returns a string with the Quaternion coordinates.
  4162. */
  4163. Quaternion.prototype.toString = function () {
  4164. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4165. };
  4166. /**
  4167. * Returns the string "Quaternion".
  4168. */
  4169. Quaternion.prototype.getClassName = function () {
  4170. return "Quaternion";
  4171. };
  4172. /**
  4173. * Returns the Quaternion hash code.
  4174. */
  4175. Quaternion.prototype.getHashCode = function () {
  4176. var hash = this.x || 0;
  4177. hash = (hash * 397) ^ (this.y || 0);
  4178. hash = (hash * 397) ^ (this.z || 0);
  4179. hash = (hash * 397) ^ (this.w || 0);
  4180. return hash;
  4181. };
  4182. /**
  4183. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4184. */
  4185. Quaternion.prototype.asArray = function () {
  4186. return [this.x, this.y, this.z, this.w];
  4187. };
  4188. /**
  4189. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4190. */
  4191. Quaternion.prototype.equals = function (otherQuaternion) {
  4192. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4193. };
  4194. /**
  4195. * Returns a new Quaternion copied from the current one.
  4196. */
  4197. Quaternion.prototype.clone = function () {
  4198. return new Quaternion(this.x, this.y, this.z, this.w);
  4199. };
  4200. /**
  4201. * Updates the current Quaternion from the passed one coordinates.
  4202. * Returns the updated Quaterion.
  4203. */
  4204. Quaternion.prototype.copyFrom = function (other) {
  4205. this.x = other.x;
  4206. this.y = other.y;
  4207. this.z = other.z;
  4208. this.w = other.w;
  4209. return this;
  4210. };
  4211. /**
  4212. * Updates the current Quaternion from the passed float coordinates.
  4213. * Returns the updated Quaterion.
  4214. */
  4215. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4216. this.x = x;
  4217. this.y = y;
  4218. this.z = z;
  4219. this.w = w;
  4220. return this;
  4221. };
  4222. /**
  4223. * Updates the current Quaternion from the passed float coordinates.
  4224. * Returns the updated Quaterion.
  4225. */
  4226. Quaternion.prototype.set = function (x, y, z, w) {
  4227. return this.copyFromFloats(x, y, z, w);
  4228. };
  4229. /**
  4230. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4231. */
  4232. Quaternion.prototype.add = function (other) {
  4233. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4234. };
  4235. /**
  4236. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4237. */
  4238. Quaternion.prototype.subtract = function (other) {
  4239. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4240. };
  4241. /**
  4242. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4243. */
  4244. Quaternion.prototype.scale = function (value) {
  4245. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4246. };
  4247. /**
  4248. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4249. */
  4250. Quaternion.prototype.multiply = function (q1) {
  4251. var result = new Quaternion(0, 0, 0, 1.0);
  4252. this.multiplyToRef(q1, result);
  4253. return result;
  4254. };
  4255. /**
  4256. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4257. * Returns the current Quaternion.
  4258. */
  4259. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4260. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4261. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4262. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4263. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4264. result.copyFromFloats(x, y, z, w);
  4265. return this;
  4266. };
  4267. /**
  4268. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4269. * Returns the updated Quaternion.
  4270. */
  4271. Quaternion.prototype.multiplyInPlace = function (q1) {
  4272. this.multiplyToRef(q1, this);
  4273. return this;
  4274. };
  4275. /**
  4276. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4277. * Returns the current Quaternion.
  4278. */
  4279. Quaternion.prototype.conjugateToRef = function (ref) {
  4280. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4281. return this;
  4282. };
  4283. /**
  4284. * Conjugates in place the current Quaternion.
  4285. * Returns the updated Quaternion.
  4286. */
  4287. Quaternion.prototype.conjugateInPlace = function () {
  4288. this.x *= -1;
  4289. this.y *= -1;
  4290. this.z *= -1;
  4291. return this;
  4292. };
  4293. /**
  4294. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4295. */
  4296. Quaternion.prototype.conjugate = function () {
  4297. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4298. return result;
  4299. };
  4300. /**
  4301. * Returns the Quaternion length (float).
  4302. */
  4303. Quaternion.prototype.length = function () {
  4304. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4305. };
  4306. /**
  4307. * Normalize in place the current Quaternion.
  4308. * Returns the updated Quaternion.
  4309. */
  4310. Quaternion.prototype.normalize = function () {
  4311. var length = 1.0 / this.length();
  4312. this.x *= length;
  4313. this.y *= length;
  4314. this.z *= length;
  4315. this.w *= length;
  4316. return this;
  4317. };
  4318. /**
  4319. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4320. */
  4321. Quaternion.prototype.toEulerAngles = function (order) {
  4322. if (order === void 0) { order = "YZX"; }
  4323. var result = Vector3.Zero();
  4324. this.toEulerAnglesToRef(result, order);
  4325. return result;
  4326. };
  4327. /**
  4328. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4329. * Returns the current Quaternion.
  4330. */
  4331. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4332. if (order === void 0) { order = "YZX"; }
  4333. var qz = this.z;
  4334. var qx = this.x;
  4335. var qy = this.y;
  4336. var qw = this.w;
  4337. var sqw = qw * qw;
  4338. var sqz = qz * qz;
  4339. var sqx = qx * qx;
  4340. var sqy = qy * qy;
  4341. var zAxisY = qy * qz - qx * qw;
  4342. var limit = .4999999;
  4343. if (zAxisY < -limit) {
  4344. result.y = 2 * Math.atan2(qy, qw);
  4345. result.x = Math.PI / 2;
  4346. result.z = 0;
  4347. }
  4348. else if (zAxisY > limit) {
  4349. result.y = 2 * Math.atan2(qy, qw);
  4350. result.x = -Math.PI / 2;
  4351. result.z = 0;
  4352. }
  4353. else {
  4354. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4355. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4356. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4357. }
  4358. return this;
  4359. };
  4360. /**
  4361. * Updates the passed rotation matrix with the current Quaternion values.
  4362. * Returns the current Quaternion.
  4363. */
  4364. Quaternion.prototype.toRotationMatrix = function (result) {
  4365. var xx = this.x * this.x;
  4366. var yy = this.y * this.y;
  4367. var zz = this.z * this.z;
  4368. var xy = this.x * this.y;
  4369. var zw = this.z * this.w;
  4370. var zx = this.z * this.x;
  4371. var yw = this.y * this.w;
  4372. var yz = this.y * this.z;
  4373. var xw = this.x * this.w;
  4374. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4375. result.m[1] = 2.0 * (xy + zw);
  4376. result.m[2] = 2.0 * (zx - yw);
  4377. result.m[3] = 0;
  4378. result.m[4] = 2.0 * (xy - zw);
  4379. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4380. result.m[6] = 2.0 * (yz + xw);
  4381. result.m[7] = 0;
  4382. result.m[8] = 2.0 * (zx + yw);
  4383. result.m[9] = 2.0 * (yz - xw);
  4384. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4385. result.m[11] = 0;
  4386. result.m[12] = 0;
  4387. result.m[13] = 0;
  4388. result.m[14] = 0;
  4389. result.m[15] = 1.0;
  4390. result._markAsUpdated();
  4391. return this;
  4392. };
  4393. /**
  4394. * Updates the current Quaternion from the passed rotation matrix values.
  4395. * Returns the updated Quaternion.
  4396. */
  4397. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4398. Quaternion.FromRotationMatrixToRef(matrix, this);
  4399. return this;
  4400. };
  4401. // Statics
  4402. /**
  4403. * Returns a new Quaternion set from the passed rotation matrix values.
  4404. */
  4405. Quaternion.FromRotationMatrix = function (matrix) {
  4406. var result = new Quaternion();
  4407. Quaternion.FromRotationMatrixToRef(matrix, result);
  4408. return result;
  4409. };
  4410. /**
  4411. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4412. */
  4413. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4414. var data = matrix.m;
  4415. var m11 = data[0], m12 = data[4], m13 = data[8];
  4416. var m21 = data[1], m22 = data[5], m23 = data[9];
  4417. var m31 = data[2], m32 = data[6], m33 = data[10];
  4418. var trace = m11 + m22 + m33;
  4419. var s;
  4420. if (trace > 0) {
  4421. s = 0.5 / Math.sqrt(trace + 1.0);
  4422. result.w = 0.25 / s;
  4423. result.x = (m32 - m23) * s;
  4424. result.y = (m13 - m31) * s;
  4425. result.z = (m21 - m12) * s;
  4426. }
  4427. else if (m11 > m22 && m11 > m33) {
  4428. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4429. result.w = (m32 - m23) / s;
  4430. result.x = 0.25 * s;
  4431. result.y = (m12 + m21) / s;
  4432. result.z = (m13 + m31) / s;
  4433. }
  4434. else if (m22 > m33) {
  4435. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4436. result.w = (m13 - m31) / s;
  4437. result.x = (m12 + m21) / s;
  4438. result.y = 0.25 * s;
  4439. result.z = (m23 + m32) / s;
  4440. }
  4441. else {
  4442. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4443. result.w = (m21 - m12) / s;
  4444. result.x = (m13 + m31) / s;
  4445. result.y = (m23 + m32) / s;
  4446. result.z = 0.25 * s;
  4447. }
  4448. };
  4449. /**
  4450. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4451. */
  4452. Quaternion.Zero = function () {
  4453. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4454. };
  4455. /**
  4456. * Returns a new Quaternion as the inverted current Quaternion.
  4457. */
  4458. Quaternion.Inverse = function (q) {
  4459. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4460. };
  4461. /**
  4462. * Returns the identity Quaternion.
  4463. */
  4464. Quaternion.Identity = function () {
  4465. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4466. };
  4467. Quaternion.IsIdentity = function (quaternion) {
  4468. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4469. };
  4470. /**
  4471. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4472. */
  4473. Quaternion.RotationAxis = function (axis, angle) {
  4474. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4475. };
  4476. /**
  4477. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4478. */
  4479. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4480. var sin = Math.sin(angle / 2);
  4481. axis.normalize();
  4482. result.w = Math.cos(angle / 2);
  4483. result.x = axis.x * sin;
  4484. result.y = axis.y * sin;
  4485. result.z = axis.z * sin;
  4486. return result;
  4487. };
  4488. /**
  4489. * Retuns a new Quaternion set from the starting index of the passed array.
  4490. */
  4491. Quaternion.FromArray = function (array, offset) {
  4492. if (!offset) {
  4493. offset = 0;
  4494. }
  4495. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4496. };
  4497. /**
  4498. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4499. */
  4500. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4501. var q = new Quaternion();
  4502. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4503. return q;
  4504. };
  4505. /**
  4506. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4507. */
  4508. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4509. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4510. var halfRoll = roll * 0.5;
  4511. var halfPitch = pitch * 0.5;
  4512. var halfYaw = yaw * 0.5;
  4513. var sinRoll = Math.sin(halfRoll);
  4514. var cosRoll = Math.cos(halfRoll);
  4515. var sinPitch = Math.sin(halfPitch);
  4516. var cosPitch = Math.cos(halfPitch);
  4517. var sinYaw = Math.sin(halfYaw);
  4518. var cosYaw = Math.cos(halfYaw);
  4519. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4520. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4521. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4522. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4523. };
  4524. /**
  4525. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4526. */
  4527. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4528. var result = new Quaternion();
  4529. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4530. return result;
  4531. };
  4532. /**
  4533. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4534. */
  4535. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4536. // Produces a quaternion from Euler angles in the z-x-z orientation
  4537. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4538. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4539. var halfBeta = beta * 0.5;
  4540. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4541. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4542. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4543. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4544. };
  4545. /**
  4546. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4547. * cf to Vector3.RotationFromAxis() documentation.
  4548. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4549. */
  4550. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4551. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4552. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4553. return quat;
  4554. };
  4555. /**
  4556. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4557. * cf to Vector3.RotationFromAxis() documentation.
  4558. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4559. */
  4560. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4561. var rotMat = MathTmp.Matrix[0];
  4562. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4563. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4564. };
  4565. Quaternion.Slerp = function (left, right, amount) {
  4566. var result = Quaternion.Identity();
  4567. Quaternion.SlerpToRef(left, right, amount, result);
  4568. return result;
  4569. };
  4570. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4571. var num2;
  4572. var num3;
  4573. var num = amount;
  4574. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4575. var flag = false;
  4576. if (num4 < 0) {
  4577. flag = true;
  4578. num4 = -num4;
  4579. }
  4580. if (num4 > 0.999999) {
  4581. num3 = 1 - num;
  4582. num2 = flag ? -num : num;
  4583. }
  4584. else {
  4585. var num5 = Math.acos(num4);
  4586. var num6 = (1.0 / Math.sin(num5));
  4587. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4588. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4589. }
  4590. result.x = (num3 * left.x) + (num2 * right.x);
  4591. result.y = (num3 * left.y) + (num2 * right.y);
  4592. result.z = (num3 * left.z) + (num2 * right.z);
  4593. result.w = (num3 * left.w) + (num2 * right.w);
  4594. };
  4595. /**
  4596. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4597. */
  4598. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4599. var squared = amount * amount;
  4600. var cubed = amount * squared;
  4601. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4602. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4603. var part3 = (cubed - (2.0 * squared)) + amount;
  4604. var part4 = cubed - squared;
  4605. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4606. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4607. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4608. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4609. return new Quaternion(x, y, z, w);
  4610. };
  4611. return Quaternion;
  4612. }());
  4613. BABYLON.Quaternion = Quaternion;
  4614. var Matrix = /** @class */ (function () {
  4615. function Matrix() {
  4616. this._isIdentity = false;
  4617. this._isIdentityDirty = true;
  4618. this.m = new Float32Array(16);
  4619. this._markAsUpdated();
  4620. }
  4621. Matrix.prototype._markAsUpdated = function () {
  4622. this.updateFlag = Matrix._updateFlagSeed++;
  4623. this._isIdentityDirty = true;
  4624. };
  4625. // Properties
  4626. /**
  4627. * Boolean : True is the matrix is the identity matrix
  4628. */
  4629. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4630. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4631. if (this._isIdentityDirty) {
  4632. this._isIdentityDirty = false;
  4633. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4634. this._isIdentity = false;
  4635. }
  4636. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4637. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4638. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4639. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4640. this._isIdentity = false;
  4641. }
  4642. else {
  4643. this._isIdentity = true;
  4644. }
  4645. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4646. this._isIdentity = false;
  4647. }
  4648. }
  4649. return this._isIdentity;
  4650. };
  4651. /**
  4652. * Returns the matrix determinant (float).
  4653. */
  4654. Matrix.prototype.determinant = function () {
  4655. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4656. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4657. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4658. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4659. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4660. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4661. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4662. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4663. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4664. };
  4665. // Methods
  4666. /**
  4667. * Returns the matrix underlying array.
  4668. */
  4669. Matrix.prototype.toArray = function () {
  4670. return this.m;
  4671. };
  4672. /**
  4673. * Returns the matrix underlying array.
  4674. */
  4675. Matrix.prototype.asArray = function () {
  4676. return this.toArray();
  4677. };
  4678. /**
  4679. * Inverts in place the Matrix.
  4680. * Returns the Matrix inverted.
  4681. */
  4682. Matrix.prototype.invert = function () {
  4683. this.invertToRef(this);
  4684. return this;
  4685. };
  4686. /**
  4687. * Sets all the matrix elements to zero.
  4688. * Returns the Matrix.
  4689. */
  4690. Matrix.prototype.reset = function () {
  4691. for (var index = 0; index < 16; index++) {
  4692. this.m[index] = 0.0;
  4693. }
  4694. this._markAsUpdated();
  4695. return this;
  4696. };
  4697. /**
  4698. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4699. */
  4700. Matrix.prototype.add = function (other) {
  4701. var result = new Matrix();
  4702. this.addToRef(other, result);
  4703. return result;
  4704. };
  4705. /**
  4706. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4707. * Returns the Matrix.
  4708. */
  4709. Matrix.prototype.addToRef = function (other, result) {
  4710. for (var index = 0; index < 16; index++) {
  4711. result.m[index] = this.m[index] + other.m[index];
  4712. }
  4713. result._markAsUpdated();
  4714. return this;
  4715. };
  4716. /**
  4717. * Adds in place the passed matrix to the current Matrix.
  4718. * Returns the updated Matrix.
  4719. */
  4720. Matrix.prototype.addToSelf = function (other) {
  4721. for (var index = 0; index < 16; index++) {
  4722. this.m[index] += other.m[index];
  4723. }
  4724. this._markAsUpdated();
  4725. return this;
  4726. };
  4727. /**
  4728. * Sets the passed matrix with the current inverted Matrix.
  4729. * Returns the unmodified current Matrix.
  4730. */
  4731. Matrix.prototype.invertToRef = function (other) {
  4732. var l1 = this.m[0];
  4733. var l2 = this.m[1];
  4734. var l3 = this.m[2];
  4735. var l4 = this.m[3];
  4736. var l5 = this.m[4];
  4737. var l6 = this.m[5];
  4738. var l7 = this.m[6];
  4739. var l8 = this.m[7];
  4740. var l9 = this.m[8];
  4741. var l10 = this.m[9];
  4742. var l11 = this.m[10];
  4743. var l12 = this.m[11];
  4744. var l13 = this.m[12];
  4745. var l14 = this.m[13];
  4746. var l15 = this.m[14];
  4747. var l16 = this.m[15];
  4748. var l17 = (l11 * l16) - (l12 * l15);
  4749. var l18 = (l10 * l16) - (l12 * l14);
  4750. var l19 = (l10 * l15) - (l11 * l14);
  4751. var l20 = (l9 * l16) - (l12 * l13);
  4752. var l21 = (l9 * l15) - (l11 * l13);
  4753. var l22 = (l9 * l14) - (l10 * l13);
  4754. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4755. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4756. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4757. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4758. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4759. var l28 = (l7 * l16) - (l8 * l15);
  4760. var l29 = (l6 * l16) - (l8 * l14);
  4761. var l30 = (l6 * l15) - (l7 * l14);
  4762. var l31 = (l5 * l16) - (l8 * l13);
  4763. var l32 = (l5 * l15) - (l7 * l13);
  4764. var l33 = (l5 * l14) - (l6 * l13);
  4765. var l34 = (l7 * l12) - (l8 * l11);
  4766. var l35 = (l6 * l12) - (l8 * l10);
  4767. var l36 = (l6 * l11) - (l7 * l10);
  4768. var l37 = (l5 * l12) - (l8 * l9);
  4769. var l38 = (l5 * l11) - (l7 * l9);
  4770. var l39 = (l5 * l10) - (l6 * l9);
  4771. other.m[0] = l23 * l27;
  4772. other.m[4] = l24 * l27;
  4773. other.m[8] = l25 * l27;
  4774. other.m[12] = l26 * l27;
  4775. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4776. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4777. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4778. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4779. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4780. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4781. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4782. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4783. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4784. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4785. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4786. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4787. other._markAsUpdated();
  4788. return this;
  4789. };
  4790. /**
  4791. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4792. * Returns the updated Matrix.
  4793. */
  4794. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4795. this.m[12] = x;
  4796. this.m[13] = y;
  4797. this.m[14] = z;
  4798. this._markAsUpdated();
  4799. return this;
  4800. };
  4801. /**
  4802. * Inserts the translation vector in the current Matrix.
  4803. * Returns the updated Matrix.
  4804. */
  4805. Matrix.prototype.setTranslation = function (vector3) {
  4806. this.m[12] = vector3.x;
  4807. this.m[13] = vector3.y;
  4808. this.m[14] = vector3.z;
  4809. this._markAsUpdated();
  4810. return this;
  4811. };
  4812. /**
  4813. * Returns a new Vector3 as the extracted translation from the Matrix.
  4814. */
  4815. Matrix.prototype.getTranslation = function () {
  4816. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4817. };
  4818. /**
  4819. * Fill a Vector3 with the extracted translation from the Matrix.
  4820. */
  4821. Matrix.prototype.getTranslationToRef = function (result) {
  4822. result.x = this.m[12];
  4823. result.y = this.m[13];
  4824. result.z = this.m[14];
  4825. return this;
  4826. };
  4827. /**
  4828. * Remove rotation and scaling part from the Matrix.
  4829. * Returns the updated Matrix.
  4830. */
  4831. Matrix.prototype.removeRotationAndScaling = function () {
  4832. this.setRowFromFloats(0, 1, 0, 0, 0);
  4833. this.setRowFromFloats(1, 0, 1, 0, 0);
  4834. this.setRowFromFloats(2, 0, 0, 1, 0);
  4835. return this;
  4836. };
  4837. /**
  4838. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4839. */
  4840. Matrix.prototype.multiply = function (other) {
  4841. var result = new Matrix();
  4842. this.multiplyToRef(other, result);
  4843. return result;
  4844. };
  4845. /**
  4846. * Updates the current Matrix from the passed one values.
  4847. * Returns the updated Matrix.
  4848. */
  4849. Matrix.prototype.copyFrom = function (other) {
  4850. for (var index = 0; index < 16; index++) {
  4851. this.m[index] = other.m[index];
  4852. }
  4853. this._markAsUpdated();
  4854. return this;
  4855. };
  4856. /**
  4857. * Populates the passed array from the starting index with the Matrix values.
  4858. * Returns the Matrix.
  4859. */
  4860. Matrix.prototype.copyToArray = function (array, offset) {
  4861. if (offset === void 0) { offset = 0; }
  4862. for (var index = 0; index < 16; index++) {
  4863. array[offset + index] = this.m[index];
  4864. }
  4865. return this;
  4866. };
  4867. /**
  4868. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4869. */
  4870. Matrix.prototype.multiplyToRef = function (other, result) {
  4871. this.multiplyToArray(other, result.m, 0);
  4872. result._markAsUpdated();
  4873. return this;
  4874. };
  4875. /**
  4876. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4877. */
  4878. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4879. var tm0 = this.m[0];
  4880. var tm1 = this.m[1];
  4881. var tm2 = this.m[2];
  4882. var tm3 = this.m[3];
  4883. var tm4 = this.m[4];
  4884. var tm5 = this.m[5];
  4885. var tm6 = this.m[6];
  4886. var tm7 = this.m[7];
  4887. var tm8 = this.m[8];
  4888. var tm9 = this.m[9];
  4889. var tm10 = this.m[10];
  4890. var tm11 = this.m[11];
  4891. var tm12 = this.m[12];
  4892. var tm13 = this.m[13];
  4893. var tm14 = this.m[14];
  4894. var tm15 = this.m[15];
  4895. var om0 = other.m[0];
  4896. var om1 = other.m[1];
  4897. var om2 = other.m[2];
  4898. var om3 = other.m[3];
  4899. var om4 = other.m[4];
  4900. var om5 = other.m[5];
  4901. var om6 = other.m[6];
  4902. var om7 = other.m[7];
  4903. var om8 = other.m[8];
  4904. var om9 = other.m[9];
  4905. var om10 = other.m[10];
  4906. var om11 = other.m[11];
  4907. var om12 = other.m[12];
  4908. var om13 = other.m[13];
  4909. var om14 = other.m[14];
  4910. var om15 = other.m[15];
  4911. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4912. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4913. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4914. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4915. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4916. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4917. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4918. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4919. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4920. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4921. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4922. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4923. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4924. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4925. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4926. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4927. return this;
  4928. };
  4929. /**
  4930. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4931. */
  4932. Matrix.prototype.equals = function (value) {
  4933. return value &&
  4934. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4935. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4936. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4937. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4938. };
  4939. /**
  4940. * Returns a new Matrix from the current Matrix.
  4941. */
  4942. Matrix.prototype.clone = function () {
  4943. 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]);
  4944. };
  4945. /**
  4946. * Returns the string "Matrix"
  4947. */
  4948. Matrix.prototype.getClassName = function () {
  4949. return "Matrix";
  4950. };
  4951. /**
  4952. * Returns the Matrix hash code.
  4953. */
  4954. Matrix.prototype.getHashCode = function () {
  4955. var hash = this.m[0] || 0;
  4956. for (var i = 1; i < 16; i++) {
  4957. hash = (hash * 397) ^ (this.m[i] || 0);
  4958. }
  4959. return hash;
  4960. };
  4961. /**
  4962. * Decomposes the current Matrix into :
  4963. * - a scale vector3 passed as a reference to update,
  4964. * - a rotation quaternion passed as a reference to update,
  4965. * - a translation vector3 passed as a reference to update.
  4966. * Returns the true if operation was successful.
  4967. */
  4968. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4969. translation.x = this.m[12];
  4970. translation.y = this.m[13];
  4971. translation.z = this.m[14];
  4972. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4973. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4974. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4975. if (this.determinant() <= 0) {
  4976. scale.y *= -1;
  4977. }
  4978. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4979. rotation.x = 0;
  4980. rotation.y = 0;
  4981. rotation.z = 0;
  4982. rotation.w = 1;
  4983. return false;
  4984. }
  4985. 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]);
  4986. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4987. return true;
  4988. };
  4989. /**
  4990. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  4991. * @param ref matrix to store the result
  4992. */
  4993. Matrix.prototype.toNormalMatrix = function (ref) {
  4994. this.invertToRef(ref);
  4995. ref.transpose();
  4996. var m = ref.m;
  4997. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  4998. };
  4999. /**
  5000. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5001. */
  5002. Matrix.prototype.getRotationMatrix = function () {
  5003. var result = Matrix.Identity();
  5004. this.getRotationMatrixToRef(result);
  5005. return result;
  5006. };
  5007. /**
  5008. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5009. * Returns the current Matrix.
  5010. */
  5011. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5012. var m = this.m;
  5013. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5014. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5015. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5016. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5017. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5018. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5019. 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);
  5020. return this;
  5021. };
  5022. // Statics
  5023. /**
  5024. * Returns a new Matrix set from the starting index of the passed array.
  5025. */
  5026. Matrix.FromArray = function (array, offset) {
  5027. var result = new Matrix();
  5028. if (!offset) {
  5029. offset = 0;
  5030. }
  5031. Matrix.FromArrayToRef(array, offset, result);
  5032. return result;
  5033. };
  5034. /**
  5035. * Sets the passed "result" matrix from the starting index of the passed array.
  5036. */
  5037. Matrix.FromArrayToRef = function (array, offset, result) {
  5038. for (var index = 0; index < 16; index++) {
  5039. result.m[index] = array[index + offset];
  5040. }
  5041. result._markAsUpdated();
  5042. };
  5043. /**
  5044. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5045. */
  5046. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5047. for (var index = 0; index < 16; index++) {
  5048. result.m[index] = array[index + offset] * scale;
  5049. }
  5050. result._markAsUpdated();
  5051. };
  5052. /**
  5053. * Sets the passed matrix "result" with the 16 passed floats.
  5054. */
  5055. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5056. result.m[0] = initialM11;
  5057. result.m[1] = initialM12;
  5058. result.m[2] = initialM13;
  5059. result.m[3] = initialM14;
  5060. result.m[4] = initialM21;
  5061. result.m[5] = initialM22;
  5062. result.m[6] = initialM23;
  5063. result.m[7] = initialM24;
  5064. result.m[8] = initialM31;
  5065. result.m[9] = initialM32;
  5066. result.m[10] = initialM33;
  5067. result.m[11] = initialM34;
  5068. result.m[12] = initialM41;
  5069. result.m[13] = initialM42;
  5070. result.m[14] = initialM43;
  5071. result.m[15] = initialM44;
  5072. result._markAsUpdated();
  5073. };
  5074. /**
  5075. * Returns the index-th row of the current matrix as a new Vector4.
  5076. */
  5077. Matrix.prototype.getRow = function (index) {
  5078. if (index < 0 || index > 3) {
  5079. return null;
  5080. }
  5081. var i = index * 4;
  5082. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5083. };
  5084. /**
  5085. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5086. * Returns the updated Matrix.
  5087. */
  5088. Matrix.prototype.setRow = function (index, row) {
  5089. if (index < 0 || index > 3) {
  5090. return this;
  5091. }
  5092. var i = index * 4;
  5093. this.m[i + 0] = row.x;
  5094. this.m[i + 1] = row.y;
  5095. this.m[i + 2] = row.z;
  5096. this.m[i + 3] = row.w;
  5097. this._markAsUpdated();
  5098. return this;
  5099. };
  5100. /**
  5101. * Compute the transpose of the matrix.
  5102. * Returns a new Matrix.
  5103. */
  5104. Matrix.prototype.transpose = function () {
  5105. return Matrix.Transpose(this);
  5106. };
  5107. /**
  5108. * Compute the transpose of the matrix.
  5109. * Returns the current matrix.
  5110. */
  5111. Matrix.prototype.transposeToRef = function (result) {
  5112. Matrix.TransposeToRef(this, result);
  5113. return this;
  5114. };
  5115. /**
  5116. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5117. * Returns the updated Matrix.
  5118. */
  5119. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5120. if (index < 0 || index > 3) {
  5121. return this;
  5122. }
  5123. var i = index * 4;
  5124. this.m[i + 0] = x;
  5125. this.m[i + 1] = y;
  5126. this.m[i + 2] = z;
  5127. this.m[i + 3] = w;
  5128. this._markAsUpdated();
  5129. return this;
  5130. };
  5131. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5132. /**
  5133. * Static identity matrix to be used as readonly matrix
  5134. * Must not be updated.
  5135. */
  5136. get: function () {
  5137. return Matrix._identityReadOnly;
  5138. },
  5139. enumerable: true,
  5140. configurable: true
  5141. });
  5142. /**
  5143. * Returns a new Matrix set from the 16 passed floats.
  5144. */
  5145. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5146. var result = new Matrix();
  5147. result.m[0] = initialM11;
  5148. result.m[1] = initialM12;
  5149. result.m[2] = initialM13;
  5150. result.m[3] = initialM14;
  5151. result.m[4] = initialM21;
  5152. result.m[5] = initialM22;
  5153. result.m[6] = initialM23;
  5154. result.m[7] = initialM24;
  5155. result.m[8] = initialM31;
  5156. result.m[9] = initialM32;
  5157. result.m[10] = initialM33;
  5158. result.m[11] = initialM34;
  5159. result.m[12] = initialM41;
  5160. result.m[13] = initialM42;
  5161. result.m[14] = initialM43;
  5162. result.m[15] = initialM44;
  5163. return result;
  5164. };
  5165. /**
  5166. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5167. */
  5168. Matrix.Compose = function (scale, rotation, translation) {
  5169. var result = Matrix.Identity();
  5170. Matrix.ComposeToRef(scale, rotation, translation, result);
  5171. return result;
  5172. };
  5173. /**
  5174. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5175. */
  5176. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5177. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5178. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5179. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5180. result.setTranslation(translation);
  5181. };
  5182. /**
  5183. * Returns a new indentity Matrix.
  5184. */
  5185. Matrix.Identity = function () {
  5186. 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);
  5187. };
  5188. /**
  5189. * Sets the passed "result" as an identity matrix.
  5190. */
  5191. Matrix.IdentityToRef = function (result) {
  5192. 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);
  5193. };
  5194. /**
  5195. * Returns a new zero Matrix.
  5196. */
  5197. Matrix.Zero = function () {
  5198. 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);
  5199. };
  5200. /**
  5201. * Returns a new rotation matrix for "angle" radians around the X axis.
  5202. */
  5203. Matrix.RotationX = function (angle) {
  5204. var result = new Matrix();
  5205. Matrix.RotationXToRef(angle, result);
  5206. return result;
  5207. };
  5208. /**
  5209. * Returns a new Matrix as the passed inverted one.
  5210. */
  5211. Matrix.Invert = function (source) {
  5212. var result = new Matrix();
  5213. source.invertToRef(result);
  5214. return result;
  5215. };
  5216. /**
  5217. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5218. */
  5219. Matrix.RotationXToRef = function (angle, result) {
  5220. var s = Math.sin(angle);
  5221. var c = Math.cos(angle);
  5222. result.m[0] = 1.0;
  5223. result.m[15] = 1.0;
  5224. result.m[5] = c;
  5225. result.m[10] = c;
  5226. result.m[9] = -s;
  5227. result.m[6] = s;
  5228. result.m[1] = 0.0;
  5229. result.m[2] = 0.0;
  5230. result.m[3] = 0.0;
  5231. result.m[4] = 0.0;
  5232. result.m[7] = 0.0;
  5233. result.m[8] = 0.0;
  5234. result.m[11] = 0.0;
  5235. result.m[12] = 0.0;
  5236. result.m[13] = 0.0;
  5237. result.m[14] = 0.0;
  5238. result._markAsUpdated();
  5239. };
  5240. /**
  5241. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5242. */
  5243. Matrix.RotationY = function (angle) {
  5244. var result = new Matrix();
  5245. Matrix.RotationYToRef(angle, result);
  5246. return result;
  5247. };
  5248. /**
  5249. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5250. */
  5251. Matrix.RotationYToRef = function (angle, result) {
  5252. var s = Math.sin(angle);
  5253. var c = Math.cos(angle);
  5254. result.m[5] = 1.0;
  5255. result.m[15] = 1.0;
  5256. result.m[0] = c;
  5257. result.m[2] = -s;
  5258. result.m[8] = s;
  5259. result.m[10] = c;
  5260. result.m[1] = 0.0;
  5261. result.m[3] = 0.0;
  5262. result.m[4] = 0.0;
  5263. result.m[6] = 0.0;
  5264. result.m[7] = 0.0;
  5265. result.m[9] = 0.0;
  5266. result.m[11] = 0.0;
  5267. result.m[12] = 0.0;
  5268. result.m[13] = 0.0;
  5269. result.m[14] = 0.0;
  5270. result._markAsUpdated();
  5271. };
  5272. /**
  5273. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5274. */
  5275. Matrix.RotationZ = function (angle) {
  5276. var result = new Matrix();
  5277. Matrix.RotationZToRef(angle, result);
  5278. return result;
  5279. };
  5280. /**
  5281. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5282. */
  5283. Matrix.RotationZToRef = function (angle, result) {
  5284. var s = Math.sin(angle);
  5285. var c = Math.cos(angle);
  5286. result.m[10] = 1.0;
  5287. result.m[15] = 1.0;
  5288. result.m[0] = c;
  5289. result.m[1] = s;
  5290. result.m[4] = -s;
  5291. result.m[5] = c;
  5292. result.m[2] = 0.0;
  5293. result.m[3] = 0.0;
  5294. result.m[6] = 0.0;
  5295. result.m[7] = 0.0;
  5296. result.m[8] = 0.0;
  5297. result.m[9] = 0.0;
  5298. result.m[11] = 0.0;
  5299. result.m[12] = 0.0;
  5300. result.m[13] = 0.0;
  5301. result.m[14] = 0.0;
  5302. result._markAsUpdated();
  5303. };
  5304. /**
  5305. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5306. */
  5307. Matrix.RotationAxis = function (axis, angle) {
  5308. var result = Matrix.Zero();
  5309. Matrix.RotationAxisToRef(axis, angle, result);
  5310. return result;
  5311. };
  5312. /**
  5313. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5314. */
  5315. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5316. var s = Math.sin(-angle);
  5317. var c = Math.cos(-angle);
  5318. var c1 = 1 - c;
  5319. axis.normalize();
  5320. result.m[0] = (axis.x * axis.x) * c1 + c;
  5321. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5322. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5323. result.m[3] = 0.0;
  5324. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5325. result.m[5] = (axis.y * axis.y) * c1 + c;
  5326. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5327. result.m[7] = 0.0;
  5328. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5329. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5330. result.m[10] = (axis.z * axis.z) * c1 + c;
  5331. result.m[11] = 0.0;
  5332. result.m[15] = 1.0;
  5333. result._markAsUpdated();
  5334. };
  5335. /**
  5336. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5337. */
  5338. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5339. var result = new Matrix();
  5340. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5341. return result;
  5342. };
  5343. /**
  5344. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5345. */
  5346. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5347. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5348. this._tempQuaternion.toRotationMatrix(result);
  5349. };
  5350. /**
  5351. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5352. */
  5353. Matrix.Scaling = function (x, y, z) {
  5354. var result = Matrix.Zero();
  5355. Matrix.ScalingToRef(x, y, z, result);
  5356. return result;
  5357. };
  5358. /**
  5359. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5360. */
  5361. Matrix.ScalingToRef = function (x, y, z, result) {
  5362. result.m[0] = x;
  5363. result.m[1] = 0.0;
  5364. result.m[2] = 0.0;
  5365. result.m[3] = 0.0;
  5366. result.m[4] = 0.0;
  5367. result.m[5] = y;
  5368. result.m[6] = 0.0;
  5369. result.m[7] = 0.0;
  5370. result.m[8] = 0.0;
  5371. result.m[9] = 0.0;
  5372. result.m[10] = z;
  5373. result.m[11] = 0.0;
  5374. result.m[12] = 0.0;
  5375. result.m[13] = 0.0;
  5376. result.m[14] = 0.0;
  5377. result.m[15] = 1.0;
  5378. result._markAsUpdated();
  5379. };
  5380. /**
  5381. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5382. */
  5383. Matrix.Translation = function (x, y, z) {
  5384. var result = Matrix.Identity();
  5385. Matrix.TranslationToRef(x, y, z, result);
  5386. return result;
  5387. };
  5388. /**
  5389. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5390. */
  5391. Matrix.TranslationToRef = function (x, y, z, result) {
  5392. 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);
  5393. };
  5394. /**
  5395. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5396. */
  5397. Matrix.Lerp = function (startValue, endValue, gradient) {
  5398. var result = Matrix.Zero();
  5399. for (var index = 0; index < 16; index++) {
  5400. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5401. }
  5402. result._markAsUpdated();
  5403. return result;
  5404. };
  5405. /**
  5406. * Returns a new Matrix whose values are computed by :
  5407. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5408. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5409. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5410. */
  5411. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5412. var startScale = new Vector3(0, 0, 0);
  5413. var startRotation = new Quaternion();
  5414. var startTranslation = new Vector3(0, 0, 0);
  5415. startValue.decompose(startScale, startRotation, startTranslation);
  5416. var endScale = new Vector3(0, 0, 0);
  5417. var endRotation = new Quaternion();
  5418. var endTranslation = new Vector3(0, 0, 0);
  5419. endValue.decompose(endScale, endRotation, endTranslation);
  5420. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5421. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5422. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5423. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5424. };
  5425. /**
  5426. * 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".
  5427. * This methods works for a Left-Handed system.
  5428. */
  5429. Matrix.LookAtLH = function (eye, target, up) {
  5430. var result = Matrix.Zero();
  5431. Matrix.LookAtLHToRef(eye, target, up, result);
  5432. return result;
  5433. };
  5434. /**
  5435. * 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".
  5436. * This methods works for a Left-Handed system.
  5437. */
  5438. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5439. // Z axis
  5440. target.subtractToRef(eye, this._zAxis);
  5441. this._zAxis.normalize();
  5442. // X axis
  5443. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5444. if (this._xAxis.lengthSquared() === 0) {
  5445. this._xAxis.x = 1.0;
  5446. }
  5447. else {
  5448. this._xAxis.normalize();
  5449. }
  5450. // Y axis
  5451. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5452. this._yAxis.normalize();
  5453. // Eye angles
  5454. var ex = -Vector3.Dot(this._xAxis, eye);
  5455. var ey = -Vector3.Dot(this._yAxis, eye);
  5456. var ez = -Vector3.Dot(this._zAxis, eye);
  5457. 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);
  5458. };
  5459. /**
  5460. * 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".
  5461. * This methods works for a Right-Handed system.
  5462. */
  5463. Matrix.LookAtRH = function (eye, target, up) {
  5464. var result = Matrix.Zero();
  5465. Matrix.LookAtRHToRef(eye, target, up, result);
  5466. return result;
  5467. };
  5468. /**
  5469. * 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".
  5470. * This methods works for a Left-Handed system.
  5471. */
  5472. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5473. // Z axis
  5474. eye.subtractToRef(target, this._zAxis);
  5475. this._zAxis.normalize();
  5476. // X axis
  5477. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5478. if (this._xAxis.lengthSquared() === 0) {
  5479. this._xAxis.x = 1.0;
  5480. }
  5481. else {
  5482. this._xAxis.normalize();
  5483. }
  5484. // Y axis
  5485. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5486. this._yAxis.normalize();
  5487. // Eye angles
  5488. var ex = -Vector3.Dot(this._xAxis, eye);
  5489. var ey = -Vector3.Dot(this._yAxis, eye);
  5490. var ez = -Vector3.Dot(this._zAxis, eye);
  5491. 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);
  5492. };
  5493. /**
  5494. * 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.
  5495. */
  5496. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5497. var matrix = Matrix.Zero();
  5498. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5499. return matrix;
  5500. };
  5501. /**
  5502. * 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.
  5503. */
  5504. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5505. var n = znear;
  5506. var f = zfar;
  5507. var a = 2.0 / width;
  5508. var b = 2.0 / height;
  5509. var c = 2.0 / (f - n);
  5510. var d = -(f + n) / (f - n);
  5511. 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);
  5512. };
  5513. /**
  5514. * 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.
  5515. */
  5516. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5517. var matrix = Matrix.Zero();
  5518. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5519. return matrix;
  5520. };
  5521. /**
  5522. * 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.
  5523. */
  5524. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5525. var n = znear;
  5526. var f = zfar;
  5527. var a = 2.0 / (right - left);
  5528. var b = 2.0 / (top - bottom);
  5529. var c = 2.0 / (f - n);
  5530. var d = -(f + n) / (f - n);
  5531. var i0 = (left + right) / (left - right);
  5532. var i1 = (top + bottom) / (bottom - top);
  5533. 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);
  5534. };
  5535. /**
  5536. * 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.
  5537. */
  5538. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5539. var matrix = Matrix.Zero();
  5540. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5541. return matrix;
  5542. };
  5543. /**
  5544. * 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.
  5545. */
  5546. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5547. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5548. result.m[10] *= -1.0;
  5549. };
  5550. /**
  5551. * 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.
  5552. */
  5553. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5554. var matrix = Matrix.Zero();
  5555. var n = znear;
  5556. var f = zfar;
  5557. var a = 2.0 * n / width;
  5558. var b = 2.0 * n / height;
  5559. var c = (f + n) / (f - n);
  5560. var d = -2.0 * f * n / (f - n);
  5561. 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);
  5562. return matrix;
  5563. };
  5564. /**
  5565. * 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.
  5566. */
  5567. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5568. var matrix = Matrix.Zero();
  5569. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5570. return matrix;
  5571. };
  5572. /**
  5573. * 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.
  5574. */
  5575. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5576. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5577. var n = znear;
  5578. var f = zfar;
  5579. var t = 1.0 / (Math.tan(fov * 0.5));
  5580. var a = isVerticalFovFixed ? (t / aspect) : t;
  5581. var b = isVerticalFovFixed ? t : (t * aspect);
  5582. var c = (f + n) / (f - n);
  5583. var d = -2.0 * f * n / (f - n);
  5584. 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);
  5585. };
  5586. /**
  5587. * 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.
  5588. */
  5589. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5590. var matrix = Matrix.Zero();
  5591. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5592. return matrix;
  5593. };
  5594. /**
  5595. * 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.
  5596. */
  5597. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5598. //alternatively this could be expressed as:
  5599. // m = PerspectiveFovLHToRef
  5600. // m[10] *= -1.0;
  5601. // m[11] *= -1.0;
  5602. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5603. var n = znear;
  5604. var f = zfar;
  5605. var t = 1.0 / (Math.tan(fov * 0.5));
  5606. var a = isVerticalFovFixed ? (t / aspect) : t;
  5607. var b = isVerticalFovFixed ? t : (t * aspect);
  5608. var c = -(f + n) / (f - n);
  5609. var d = -2 * f * n / (f - n);
  5610. 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);
  5611. };
  5612. /**
  5613. * 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.
  5614. */
  5615. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5616. if (rightHanded === void 0) { rightHanded = false; }
  5617. var rightHandedFactor = rightHanded ? -1 : 1;
  5618. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5619. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5620. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5621. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5622. var xScale = 2.0 / (leftTan + rightTan);
  5623. var yScale = 2.0 / (upTan + downTan);
  5624. result.m[0] = xScale;
  5625. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5626. result.m[5] = yScale;
  5627. result.m[6] = result.m[7] = 0.0;
  5628. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5629. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5630. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5631. result.m[10] = -zfar / (znear - zfar);
  5632. result.m[11] = 1.0 * rightHandedFactor;
  5633. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5634. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5635. // result.m[14] = (znear * zfar) / (znear - zfar);
  5636. result._markAsUpdated();
  5637. };
  5638. /**
  5639. * Returns the final transformation matrix : world * view * projection * viewport
  5640. */
  5641. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5642. var cw = viewport.width;
  5643. var ch = viewport.height;
  5644. var cx = viewport.x;
  5645. var cy = viewport.y;
  5646. 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);
  5647. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5648. };
  5649. /**
  5650. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5651. */
  5652. Matrix.GetAsMatrix2x2 = function (matrix) {
  5653. return new Float32Array([
  5654. matrix.m[0], matrix.m[1],
  5655. matrix.m[4], matrix.m[5]
  5656. ]);
  5657. };
  5658. /**
  5659. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5660. */
  5661. Matrix.GetAsMatrix3x3 = function (matrix) {
  5662. return new Float32Array([
  5663. matrix.m[0], matrix.m[1], matrix.m[2],
  5664. matrix.m[4], matrix.m[5], matrix.m[6],
  5665. matrix.m[8], matrix.m[9], matrix.m[10]
  5666. ]);
  5667. };
  5668. /**
  5669. * Compute the transpose of the passed Matrix.
  5670. * Returns a new Matrix.
  5671. */
  5672. Matrix.Transpose = function (matrix) {
  5673. var result = new Matrix();
  5674. Matrix.TransposeToRef(matrix, result);
  5675. return result;
  5676. };
  5677. /**
  5678. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5679. */
  5680. Matrix.TransposeToRef = function (matrix, result) {
  5681. result.m[0] = matrix.m[0];
  5682. result.m[1] = matrix.m[4];
  5683. result.m[2] = matrix.m[8];
  5684. result.m[3] = matrix.m[12];
  5685. result.m[4] = matrix.m[1];
  5686. result.m[5] = matrix.m[5];
  5687. result.m[6] = matrix.m[9];
  5688. result.m[7] = matrix.m[13];
  5689. result.m[8] = matrix.m[2];
  5690. result.m[9] = matrix.m[6];
  5691. result.m[10] = matrix.m[10];
  5692. result.m[11] = matrix.m[14];
  5693. result.m[12] = matrix.m[3];
  5694. result.m[13] = matrix.m[7];
  5695. result.m[14] = matrix.m[11];
  5696. result.m[15] = matrix.m[15];
  5697. };
  5698. /**
  5699. * Returns a new Matrix as the reflection matrix across the passed plane.
  5700. */
  5701. Matrix.Reflection = function (plane) {
  5702. var matrix = new Matrix();
  5703. Matrix.ReflectionToRef(plane, matrix);
  5704. return matrix;
  5705. };
  5706. /**
  5707. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5708. */
  5709. Matrix.ReflectionToRef = function (plane, result) {
  5710. plane.normalize();
  5711. var x = plane.normal.x;
  5712. var y = plane.normal.y;
  5713. var z = plane.normal.z;
  5714. var temp = -2 * x;
  5715. var temp2 = -2 * y;
  5716. var temp3 = -2 * z;
  5717. result.m[0] = (temp * x) + 1;
  5718. result.m[1] = temp2 * x;
  5719. result.m[2] = temp3 * x;
  5720. result.m[3] = 0.0;
  5721. result.m[4] = temp * y;
  5722. result.m[5] = (temp2 * y) + 1;
  5723. result.m[6] = temp3 * y;
  5724. result.m[7] = 0.0;
  5725. result.m[8] = temp * z;
  5726. result.m[9] = temp2 * z;
  5727. result.m[10] = (temp3 * z) + 1;
  5728. result.m[11] = 0.0;
  5729. result.m[12] = temp * plane.d;
  5730. result.m[13] = temp2 * plane.d;
  5731. result.m[14] = temp3 * plane.d;
  5732. result.m[15] = 1.0;
  5733. result._markAsUpdated();
  5734. };
  5735. /**
  5736. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5737. */
  5738. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5739. result.m[0] = xaxis.x;
  5740. result.m[1] = xaxis.y;
  5741. result.m[2] = xaxis.z;
  5742. result.m[3] = 0.0;
  5743. result.m[4] = yaxis.x;
  5744. result.m[5] = yaxis.y;
  5745. result.m[6] = yaxis.z;
  5746. result.m[7] = 0.0;
  5747. result.m[8] = zaxis.x;
  5748. result.m[9] = zaxis.y;
  5749. result.m[10] = zaxis.z;
  5750. result.m[11] = 0.0;
  5751. result.m[12] = 0.0;
  5752. result.m[13] = 0.0;
  5753. result.m[14] = 0.0;
  5754. result.m[15] = 1.0;
  5755. result._markAsUpdated();
  5756. };
  5757. /**
  5758. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5759. */
  5760. Matrix.FromQuaternionToRef = function (quat, result) {
  5761. var xx = quat.x * quat.x;
  5762. var yy = quat.y * quat.y;
  5763. var zz = quat.z * quat.z;
  5764. var xy = quat.x * quat.y;
  5765. var zw = quat.z * quat.w;
  5766. var zx = quat.z * quat.x;
  5767. var yw = quat.y * quat.w;
  5768. var yz = quat.y * quat.z;
  5769. var xw = quat.x * quat.w;
  5770. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5771. result.m[1] = 2.0 * (xy + zw);
  5772. result.m[2] = 2.0 * (zx - yw);
  5773. result.m[3] = 0.0;
  5774. result.m[4] = 2.0 * (xy - zw);
  5775. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5776. result.m[6] = 2.0 * (yz + xw);
  5777. result.m[7] = 0.0;
  5778. result.m[8] = 2.0 * (zx + yw);
  5779. result.m[9] = 2.0 * (yz - xw);
  5780. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5781. result.m[11] = 0.0;
  5782. result.m[12] = 0.0;
  5783. result.m[13] = 0.0;
  5784. result.m[14] = 0.0;
  5785. result.m[15] = 1.0;
  5786. result._markAsUpdated();
  5787. };
  5788. Matrix._tempQuaternion = new Quaternion();
  5789. Matrix._xAxis = Vector3.Zero();
  5790. Matrix._yAxis = Vector3.Zero();
  5791. Matrix._zAxis = Vector3.Zero();
  5792. Matrix._updateFlagSeed = 0;
  5793. Matrix._identityReadOnly = Matrix.Identity();
  5794. return Matrix;
  5795. }());
  5796. BABYLON.Matrix = Matrix;
  5797. var Plane = /** @class */ (function () {
  5798. /**
  5799. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5800. */
  5801. function Plane(a, b, c, d) {
  5802. this.normal = new Vector3(a, b, c);
  5803. this.d = d;
  5804. }
  5805. /**
  5806. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5807. */
  5808. Plane.prototype.asArray = function () {
  5809. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5810. };
  5811. // Methods
  5812. /**
  5813. * Returns a new plane copied from the current Plane.
  5814. */
  5815. Plane.prototype.clone = function () {
  5816. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5817. };
  5818. /**
  5819. * Returns the string "Plane".
  5820. */
  5821. Plane.prototype.getClassName = function () {
  5822. return "Plane";
  5823. };
  5824. /**
  5825. * Returns the Plane hash code.
  5826. */
  5827. Plane.prototype.getHashCode = function () {
  5828. var hash = this.normal.getHashCode();
  5829. hash = (hash * 397) ^ (this.d || 0);
  5830. return hash;
  5831. };
  5832. /**
  5833. * Normalize the current Plane in place.
  5834. * Returns the updated Plane.
  5835. */
  5836. Plane.prototype.normalize = function () {
  5837. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5838. var magnitude = 0.0;
  5839. if (norm !== 0) {
  5840. magnitude = 1.0 / norm;
  5841. }
  5842. this.normal.x *= magnitude;
  5843. this.normal.y *= magnitude;
  5844. this.normal.z *= magnitude;
  5845. this.d *= magnitude;
  5846. return this;
  5847. };
  5848. /**
  5849. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5850. */
  5851. Plane.prototype.transform = function (transformation) {
  5852. var transposedMatrix = Matrix.Transpose(transformation);
  5853. var x = this.normal.x;
  5854. var y = this.normal.y;
  5855. var z = this.normal.z;
  5856. var d = this.d;
  5857. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5858. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5859. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5860. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5861. return new Plane(normalX, normalY, normalZ, finalD);
  5862. };
  5863. /**
  5864. * Returns the dot product (float) of the point coordinates and the plane normal.
  5865. */
  5866. Plane.prototype.dotCoordinate = function (point) {
  5867. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5868. };
  5869. /**
  5870. * Updates the current Plane from the plane defined by the three passed points.
  5871. * Returns the updated Plane.
  5872. */
  5873. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5874. var x1 = point2.x - point1.x;
  5875. var y1 = point2.y - point1.y;
  5876. var z1 = point2.z - point1.z;
  5877. var x2 = point3.x - point1.x;
  5878. var y2 = point3.y - point1.y;
  5879. var z2 = point3.z - point1.z;
  5880. var yz = (y1 * z2) - (z1 * y2);
  5881. var xz = (z1 * x2) - (x1 * z2);
  5882. var xy = (x1 * y2) - (y1 * x2);
  5883. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5884. var invPyth;
  5885. if (pyth !== 0) {
  5886. invPyth = 1.0 / pyth;
  5887. }
  5888. else {
  5889. invPyth = 0.0;
  5890. }
  5891. this.normal.x = yz * invPyth;
  5892. this.normal.y = xz * invPyth;
  5893. this.normal.z = xy * invPyth;
  5894. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5895. return this;
  5896. };
  5897. /**
  5898. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5899. */
  5900. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5901. var dot = Vector3.Dot(this.normal, direction);
  5902. return (dot <= epsilon);
  5903. };
  5904. /**
  5905. * Returns the signed distance (float) from the passed point to the Plane.
  5906. */
  5907. Plane.prototype.signedDistanceTo = function (point) {
  5908. return Vector3.Dot(point, this.normal) + this.d;
  5909. };
  5910. // Statics
  5911. /**
  5912. * Returns a new Plane from the passed array.
  5913. */
  5914. Plane.FromArray = function (array) {
  5915. return new Plane(array[0], array[1], array[2], array[3]);
  5916. };
  5917. /**
  5918. * Returns a new Plane defined by the three passed points.
  5919. */
  5920. Plane.FromPoints = function (point1, point2, point3) {
  5921. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5922. result.copyFromPoints(point1, point2, point3);
  5923. return result;
  5924. };
  5925. /**
  5926. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5927. * Note : the vector "normal" is updated because normalized.
  5928. */
  5929. Plane.FromPositionAndNormal = function (origin, normal) {
  5930. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5931. normal.normalize();
  5932. result.normal = normal;
  5933. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5934. return result;
  5935. };
  5936. /**
  5937. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5938. */
  5939. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5940. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5941. return Vector3.Dot(point, normal) + d;
  5942. };
  5943. return Plane;
  5944. }());
  5945. BABYLON.Plane = Plane;
  5946. var Viewport = /** @class */ (function () {
  5947. /**
  5948. * Creates a Viewport object located at (x, y) and sized (width, height).
  5949. */
  5950. function Viewport(x, y, width, height) {
  5951. this.x = x;
  5952. this.y = y;
  5953. this.width = width;
  5954. this.height = height;
  5955. }
  5956. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5957. if (renderWidthOrEngine.getRenderWidth) {
  5958. var engine = renderWidthOrEngine;
  5959. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5960. }
  5961. var renderWidth = renderWidthOrEngine;
  5962. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5963. };
  5964. /**
  5965. * Returns a new Viewport copied from the current one.
  5966. */
  5967. Viewport.prototype.clone = function () {
  5968. return new Viewport(this.x, this.y, this.width, this.height);
  5969. };
  5970. return Viewport;
  5971. }());
  5972. BABYLON.Viewport = Viewport;
  5973. var Frustum = /** @class */ (function () {
  5974. function Frustum() {
  5975. }
  5976. /**
  5977. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5978. */
  5979. Frustum.GetPlanes = function (transform) {
  5980. var frustumPlanes = [];
  5981. for (var index = 0; index < 6; index++) {
  5982. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5983. }
  5984. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5985. return frustumPlanes;
  5986. };
  5987. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5988. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5989. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5990. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5991. frustumPlane.d = transform.m[15] + transform.m[14];
  5992. frustumPlane.normalize();
  5993. };
  5994. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5995. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5996. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5997. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5998. frustumPlane.d = transform.m[15] - transform.m[14];
  5999. frustumPlane.normalize();
  6000. };
  6001. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6002. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6003. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6004. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6005. frustumPlane.d = transform.m[15] + transform.m[12];
  6006. frustumPlane.normalize();
  6007. };
  6008. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6009. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6010. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6011. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6012. frustumPlane.d = transform.m[15] - transform.m[12];
  6013. frustumPlane.normalize();
  6014. };
  6015. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6016. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6017. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6018. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6019. frustumPlane.d = transform.m[15] - transform.m[13];
  6020. frustumPlane.normalize();
  6021. };
  6022. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6023. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6024. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6025. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6026. frustumPlane.d = transform.m[15] + transform.m[13];
  6027. frustumPlane.normalize();
  6028. };
  6029. /**
  6030. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6031. */
  6032. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6033. // Near
  6034. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6035. // Far
  6036. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6037. // Left
  6038. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6039. // Right
  6040. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6041. // Top
  6042. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6043. // Bottom
  6044. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6045. };
  6046. return Frustum;
  6047. }());
  6048. BABYLON.Frustum = Frustum;
  6049. var Space;
  6050. (function (Space) {
  6051. Space[Space["LOCAL"] = 0] = "LOCAL";
  6052. Space[Space["WORLD"] = 1] = "WORLD";
  6053. Space[Space["BONE"] = 2] = "BONE";
  6054. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6055. var Axis = /** @class */ (function () {
  6056. function Axis() {
  6057. }
  6058. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6059. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6060. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6061. return Axis;
  6062. }());
  6063. BABYLON.Axis = Axis;
  6064. ;
  6065. var BezierCurve = /** @class */ (function () {
  6066. function BezierCurve() {
  6067. }
  6068. /**
  6069. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6070. */
  6071. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6072. // Extract X (which is equal to time here)
  6073. var f0 = 1 - 3 * x2 + 3 * x1;
  6074. var f1 = 3 * x2 - 6 * x1;
  6075. var f2 = 3 * x1;
  6076. var refinedT = t;
  6077. for (var i = 0; i < 5; i++) {
  6078. var refinedT2 = refinedT * refinedT;
  6079. var refinedT3 = refinedT2 * refinedT;
  6080. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6081. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6082. refinedT -= (x - t) * slope;
  6083. refinedT = Math.min(1, Math.max(0, refinedT));
  6084. }
  6085. // Resolve cubic bezier for the given x
  6086. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6087. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6088. Math.pow(refinedT, 3);
  6089. };
  6090. return BezierCurve;
  6091. }());
  6092. BABYLON.BezierCurve = BezierCurve;
  6093. var Orientation;
  6094. (function (Orientation) {
  6095. Orientation[Orientation["CW"] = 0] = "CW";
  6096. Orientation[Orientation["CCW"] = 1] = "CCW";
  6097. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6098. var Angle = /** @class */ (function () {
  6099. /**
  6100. * Creates an Angle object of "radians" radians (float).
  6101. */
  6102. function Angle(radians) {
  6103. var _this = this;
  6104. /**
  6105. * Returns the Angle value in degrees (float).
  6106. */
  6107. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6108. /**
  6109. * Returns the Angle value in radians (float).
  6110. */
  6111. this.radians = function () { return _this._radians; };
  6112. this._radians = radians;
  6113. if (this._radians < 0.0)
  6114. this._radians += (2.0 * Math.PI);
  6115. }
  6116. /**
  6117. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6118. */
  6119. Angle.BetweenTwoPoints = function (a, b) {
  6120. var delta = b.subtract(a);
  6121. var theta = Math.atan2(delta.y, delta.x);
  6122. return new Angle(theta);
  6123. };
  6124. /**
  6125. * Returns a new Angle object from the passed float in radians.
  6126. */
  6127. Angle.FromRadians = function (radians) {
  6128. return new Angle(radians);
  6129. };
  6130. /**
  6131. * Returns a new Angle object from the passed float in degrees.
  6132. */
  6133. Angle.FromDegrees = function (degrees) {
  6134. return new Angle(degrees * Math.PI / 180.0);
  6135. };
  6136. return Angle;
  6137. }());
  6138. BABYLON.Angle = Angle;
  6139. var Arc2 = /** @class */ (function () {
  6140. /**
  6141. * Creates an Arc object from the three passed points : start, middle and end.
  6142. */
  6143. function Arc2(startPoint, midPoint, endPoint) {
  6144. this.startPoint = startPoint;
  6145. this.midPoint = midPoint;
  6146. this.endPoint = endPoint;
  6147. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6148. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6149. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6150. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6151. 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);
  6152. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6153. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6154. var a1 = this.startAngle.degrees();
  6155. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6156. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6157. // angles correction
  6158. if (a2 - a1 > +180.0)
  6159. a2 -= 360.0;
  6160. if (a2 - a1 < -180.0)
  6161. a2 += 360.0;
  6162. if (a3 - a2 > +180.0)
  6163. a3 -= 360.0;
  6164. if (a3 - a2 < -180.0)
  6165. a3 += 360.0;
  6166. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6167. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6168. }
  6169. return Arc2;
  6170. }());
  6171. BABYLON.Arc2 = Arc2;
  6172. var Path2 = /** @class */ (function () {
  6173. /**
  6174. * Creates a Path2 object from the starting 2D coordinates x and y.
  6175. */
  6176. function Path2(x, y) {
  6177. this._points = new Array();
  6178. this._length = 0.0;
  6179. this.closed = false;
  6180. this._points.push(new Vector2(x, y));
  6181. }
  6182. /**
  6183. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6184. * Returns the updated Path2.
  6185. */
  6186. Path2.prototype.addLineTo = function (x, y) {
  6187. if (this.closed) {
  6188. return this;
  6189. }
  6190. var newPoint = new Vector2(x, y);
  6191. var previousPoint = this._points[this._points.length - 1];
  6192. this._points.push(newPoint);
  6193. this._length += newPoint.subtract(previousPoint).length();
  6194. return this;
  6195. };
  6196. /**
  6197. * 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.
  6198. * Returns the updated Path2.
  6199. */
  6200. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6201. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6202. if (this.closed) {
  6203. return this;
  6204. }
  6205. var startPoint = this._points[this._points.length - 1];
  6206. var midPoint = new Vector2(midX, midY);
  6207. var endPoint = new Vector2(endX, endY);
  6208. var arc = new Arc2(startPoint, midPoint, endPoint);
  6209. var increment = arc.angle.radians() / numberOfSegments;
  6210. if (arc.orientation === Orientation.CW)
  6211. increment *= -1;
  6212. var currentAngle = arc.startAngle.radians() + increment;
  6213. for (var i = 0; i < numberOfSegments; i++) {
  6214. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6215. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6216. this.addLineTo(x, y);
  6217. currentAngle += increment;
  6218. }
  6219. return this;
  6220. };
  6221. /**
  6222. * Closes the Path2.
  6223. * Returns the Path2.
  6224. */
  6225. Path2.prototype.close = function () {
  6226. this.closed = true;
  6227. return this;
  6228. };
  6229. /**
  6230. * Returns the Path2 total length (float).
  6231. */
  6232. Path2.prototype.length = function () {
  6233. var result = this._length;
  6234. if (!this.closed) {
  6235. var lastPoint = this._points[this._points.length - 1];
  6236. var firstPoint = this._points[0];
  6237. result += (firstPoint.subtract(lastPoint).length());
  6238. }
  6239. return result;
  6240. };
  6241. /**
  6242. * Returns the Path2 internal array of points.
  6243. */
  6244. Path2.prototype.getPoints = function () {
  6245. return this._points;
  6246. };
  6247. /**
  6248. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6249. */
  6250. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6251. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6252. return Vector2.Zero();
  6253. }
  6254. var lengthPosition = normalizedLengthPosition * this.length();
  6255. var previousOffset = 0;
  6256. for (var i = 0; i < this._points.length; i++) {
  6257. var j = (i + 1) % this._points.length;
  6258. var a = this._points[i];
  6259. var b = this._points[j];
  6260. var bToA = b.subtract(a);
  6261. var nextOffset = (bToA.length() + previousOffset);
  6262. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6263. var dir = bToA.normalize();
  6264. var localOffset = lengthPosition - previousOffset;
  6265. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6266. }
  6267. previousOffset = nextOffset;
  6268. }
  6269. return Vector2.Zero();
  6270. };
  6271. /**
  6272. * Returns a new Path2 starting at the coordinates (x, y).
  6273. */
  6274. Path2.StartingAt = function (x, y) {
  6275. return new Path2(x, y);
  6276. };
  6277. return Path2;
  6278. }());
  6279. BABYLON.Path2 = Path2;
  6280. var Path3D = /** @class */ (function () {
  6281. /**
  6282. * new Path3D(path, normal, raw)
  6283. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6284. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6285. * path : an array of Vector3, the curve axis of the Path3D
  6286. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6287. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6288. */
  6289. function Path3D(path, firstNormal, raw) {
  6290. if (firstNormal === void 0) { firstNormal = null; }
  6291. this.path = path;
  6292. this._curve = new Array();
  6293. this._distances = new Array();
  6294. this._tangents = new Array();
  6295. this._normals = new Array();
  6296. this._binormals = new Array();
  6297. for (var p = 0; p < path.length; p++) {
  6298. this._curve[p] = path[p].clone(); // hard copy
  6299. }
  6300. this._raw = raw || false;
  6301. this._compute(firstNormal);
  6302. }
  6303. /**
  6304. * Returns the Path3D array of successive Vector3 designing its curve.
  6305. */
  6306. Path3D.prototype.getCurve = function () {
  6307. return this._curve;
  6308. };
  6309. /**
  6310. * Returns an array populated with tangent vectors on each Path3D curve point.
  6311. */
  6312. Path3D.prototype.getTangents = function () {
  6313. return this._tangents;
  6314. };
  6315. /**
  6316. * Returns an array populated with normal vectors on each Path3D curve point.
  6317. */
  6318. Path3D.prototype.getNormals = function () {
  6319. return this._normals;
  6320. };
  6321. /**
  6322. * Returns an array populated with binormal vectors on each Path3D curve point.
  6323. */
  6324. Path3D.prototype.getBinormals = function () {
  6325. return this._binormals;
  6326. };
  6327. /**
  6328. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6329. */
  6330. Path3D.prototype.getDistances = function () {
  6331. return this._distances;
  6332. };
  6333. /**
  6334. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6335. * Returns the same object updated.
  6336. */
  6337. Path3D.prototype.update = function (path, firstNormal) {
  6338. if (firstNormal === void 0) { firstNormal = null; }
  6339. for (var p = 0; p < path.length; p++) {
  6340. this._curve[p].x = path[p].x;
  6341. this._curve[p].y = path[p].y;
  6342. this._curve[p].z = path[p].z;
  6343. }
  6344. this._compute(firstNormal);
  6345. return this;
  6346. };
  6347. // private function compute() : computes tangents, normals and binormals
  6348. Path3D.prototype._compute = function (firstNormal) {
  6349. var l = this._curve.length;
  6350. // first and last tangents
  6351. this._tangents[0] = this._getFirstNonNullVector(0);
  6352. if (!this._raw) {
  6353. this._tangents[0].normalize();
  6354. }
  6355. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6356. if (!this._raw) {
  6357. this._tangents[l - 1].normalize();
  6358. }
  6359. // normals and binormals at first point : arbitrary vector with _normalVector()
  6360. var tg0 = this._tangents[0];
  6361. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6362. this._normals[0] = pp0;
  6363. if (!this._raw) {
  6364. this._normals[0].normalize();
  6365. }
  6366. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6367. if (!this._raw) {
  6368. this._binormals[0].normalize();
  6369. }
  6370. this._distances[0] = 0.0;
  6371. // normals and binormals : next points
  6372. var prev; // previous vector (segment)
  6373. var cur; // current vector (segment)
  6374. var curTang; // current tangent
  6375. // previous normal
  6376. var prevBinor; // previous binormal
  6377. for (var i = 1; i < l; i++) {
  6378. // tangents
  6379. prev = this._getLastNonNullVector(i);
  6380. if (i < l - 1) {
  6381. cur = this._getFirstNonNullVector(i);
  6382. this._tangents[i] = prev.add(cur);
  6383. this._tangents[i].normalize();
  6384. }
  6385. this._distances[i] = this._distances[i - 1] + prev.length();
  6386. // normals and binormals
  6387. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6388. curTang = this._tangents[i];
  6389. prevBinor = this._binormals[i - 1];
  6390. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6391. if (!this._raw) {
  6392. this._normals[i].normalize();
  6393. }
  6394. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6395. if (!this._raw) {
  6396. this._binormals[i].normalize();
  6397. }
  6398. }
  6399. };
  6400. // private function getFirstNonNullVector(index)
  6401. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6402. Path3D.prototype._getFirstNonNullVector = function (index) {
  6403. var i = 1;
  6404. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6405. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6406. i++;
  6407. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6408. }
  6409. return nNVector;
  6410. };
  6411. // private function getLastNonNullVector(index)
  6412. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6413. Path3D.prototype._getLastNonNullVector = function (index) {
  6414. var i = 1;
  6415. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6416. while (nLVector.length() === 0 && index > i + 1) {
  6417. i++;
  6418. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6419. }
  6420. return nLVector;
  6421. };
  6422. // private function normalVector(v0, vt, va) :
  6423. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6424. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6425. Path3D.prototype._normalVector = function (v0, vt, va) {
  6426. var normal0;
  6427. var tgl = vt.length();
  6428. if (tgl === 0.0) {
  6429. tgl = 1.0;
  6430. }
  6431. if (va === undefined || va === null) {
  6432. var point;
  6433. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6434. point = new Vector3(0.0, -1.0, 0.0);
  6435. }
  6436. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6437. point = new Vector3(1.0, 0.0, 0.0);
  6438. }
  6439. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6440. point = new Vector3(0.0, 0.0, 1.0);
  6441. }
  6442. else {
  6443. point = Vector3.Zero();
  6444. }
  6445. normal0 = Vector3.Cross(vt, point);
  6446. }
  6447. else {
  6448. normal0 = Vector3.Cross(vt, va);
  6449. Vector3.CrossToRef(normal0, vt, normal0);
  6450. }
  6451. normal0.normalize();
  6452. return normal0;
  6453. };
  6454. return Path3D;
  6455. }());
  6456. BABYLON.Path3D = Path3D;
  6457. var Curve3 = /** @class */ (function () {
  6458. /**
  6459. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6460. * A Curve3 is designed from a series of successive Vector3.
  6461. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6462. */
  6463. function Curve3(points) {
  6464. this._length = 0.0;
  6465. this._points = points;
  6466. this._length = this._computeLength(points);
  6467. }
  6468. /**
  6469. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6470. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6471. * @param v1 (Vector3) the control point
  6472. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6473. * @param nbPoints (integer) the wanted number of points in the curve
  6474. */
  6475. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6476. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6477. var bez = new Array();
  6478. var equation = function (t, val0, val1, val2) {
  6479. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6480. return res;
  6481. };
  6482. for (var i = 0; i <= nbPoints; i++) {
  6483. 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)));
  6484. }
  6485. return new Curve3(bez);
  6486. };
  6487. /**
  6488. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6489. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6490. * @param v1 (Vector3) the first control point
  6491. * @param v2 (Vector3) the second control point
  6492. * @param v3 (Vector3) the end point of the Cubic Bezier
  6493. * @param nbPoints (integer) the wanted number of points in the curve
  6494. */
  6495. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6496. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6497. var bez = new Array();
  6498. var equation = function (t, val0, val1, val2, val3) {
  6499. 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;
  6500. return res;
  6501. };
  6502. for (var i = 0; i <= nbPoints; i++) {
  6503. 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)));
  6504. }
  6505. return new Curve3(bez);
  6506. };
  6507. /**
  6508. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6509. * @param p1 (Vector3) the origin point of the Hermite Spline
  6510. * @param t1 (Vector3) the tangent vector at the origin point
  6511. * @param p2 (Vector3) the end point of the Hermite Spline
  6512. * @param t2 (Vector3) the tangent vector at the end point
  6513. * @param nbPoints (integer) the wanted number of points in the curve
  6514. */
  6515. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6516. var hermite = new Array();
  6517. var step = 1.0 / nbPoints;
  6518. for (var i = 0; i <= nbPoints; i++) {
  6519. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6520. }
  6521. return new Curve3(hermite);
  6522. };
  6523. /**
  6524. * Returns a Curve3 object along a CatmullRom Spline curve :
  6525. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6526. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6527. */
  6528. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6529. var totalPoints = new Array();
  6530. totalPoints.push(points[0].clone());
  6531. Array.prototype.push.apply(totalPoints, points);
  6532. totalPoints.push(points[points.length - 1].clone());
  6533. var catmullRom = new Array();
  6534. var step = 1.0 / nbPoints;
  6535. var amount = 0.0;
  6536. for (var i = 0; i < totalPoints.length - 3; i++) {
  6537. amount = 0;
  6538. for (var c = 0; c < nbPoints; c++) {
  6539. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6540. amount += step;
  6541. }
  6542. }
  6543. i--;
  6544. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6545. return new Curve3(catmullRom);
  6546. };
  6547. /**
  6548. * Returns the Curve3 stored array of successive Vector3
  6549. */
  6550. Curve3.prototype.getPoints = function () {
  6551. return this._points;
  6552. };
  6553. /**
  6554. * Returns the computed length (float) of the curve.
  6555. */
  6556. Curve3.prototype.length = function () {
  6557. return this._length;
  6558. };
  6559. /**
  6560. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6561. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6562. * curveA and curveB keep unchanged.
  6563. */
  6564. Curve3.prototype.continue = function (curve) {
  6565. var lastPoint = this._points[this._points.length - 1];
  6566. var continuedPoints = this._points.slice();
  6567. var curvePoints = curve.getPoints();
  6568. for (var i = 1; i < curvePoints.length; i++) {
  6569. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6570. }
  6571. var continuedCurve = new Curve3(continuedPoints);
  6572. return continuedCurve;
  6573. };
  6574. Curve3.prototype._computeLength = function (path) {
  6575. var l = 0;
  6576. for (var i = 1; i < path.length; i++) {
  6577. l += (path[i].subtract(path[i - 1])).length();
  6578. }
  6579. return l;
  6580. };
  6581. return Curve3;
  6582. }());
  6583. BABYLON.Curve3 = Curve3;
  6584. // Vertex formats
  6585. var PositionNormalVertex = /** @class */ (function () {
  6586. function PositionNormalVertex(position, normal) {
  6587. if (position === void 0) { position = Vector3.Zero(); }
  6588. if (normal === void 0) { normal = Vector3.Up(); }
  6589. this.position = position;
  6590. this.normal = normal;
  6591. }
  6592. PositionNormalVertex.prototype.clone = function () {
  6593. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6594. };
  6595. return PositionNormalVertex;
  6596. }());
  6597. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6598. var PositionNormalTextureVertex = /** @class */ (function () {
  6599. function PositionNormalTextureVertex(position, normal, uv) {
  6600. if (position === void 0) { position = Vector3.Zero(); }
  6601. if (normal === void 0) { normal = Vector3.Up(); }
  6602. if (uv === void 0) { uv = Vector2.Zero(); }
  6603. this.position = position;
  6604. this.normal = normal;
  6605. this.uv = uv;
  6606. }
  6607. PositionNormalTextureVertex.prototype.clone = function () {
  6608. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6609. };
  6610. return PositionNormalTextureVertex;
  6611. }());
  6612. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6613. // Temporary pre-allocated objects for engine internal use
  6614. // usage in any internal function :
  6615. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6616. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6617. var Tmp = /** @class */ (function () {
  6618. function Tmp() {
  6619. }
  6620. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6621. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6622. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6623. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6624. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6625. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6626. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6627. Matrix.Zero(), Matrix.Zero(),
  6628. Matrix.Zero(), Matrix.Zero(),
  6629. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6630. return Tmp;
  6631. }());
  6632. BABYLON.Tmp = Tmp;
  6633. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6634. var MathTmp = /** @class */ (function () {
  6635. function MathTmp() {
  6636. }
  6637. MathTmp.Vector3 = [Vector3.Zero()];
  6638. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6639. MathTmp.Quaternion = [Quaternion.Zero()];
  6640. return MathTmp;
  6641. }());
  6642. })(BABYLON || (BABYLON = {}));
  6643. //# sourceMappingURL=babylon.math.js.map
  6644. var BABYLON;
  6645. (function (BABYLON) {
  6646. var Scalar = /** @class */ (function () {
  6647. function Scalar() {
  6648. }
  6649. /**
  6650. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6651. */
  6652. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6653. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6654. var num = a - b;
  6655. return -epsilon <= num && num <= epsilon;
  6656. };
  6657. /**
  6658. * Returns a string : the upper case translation of the number i to hexadecimal.
  6659. */
  6660. Scalar.ToHex = function (i) {
  6661. var str = i.toString(16);
  6662. if (i <= 15) {
  6663. return ("0" + str).toUpperCase();
  6664. }
  6665. return str.toUpperCase();
  6666. };
  6667. /**
  6668. * Returns -1 if value is negative and +1 is value is positive.
  6669. * Returns the value itself if it's equal to zero.
  6670. */
  6671. Scalar.Sign = function (value) {
  6672. value = +value; // convert to a number
  6673. if (value === 0 || isNaN(value))
  6674. return value;
  6675. return value > 0 ? 1 : -1;
  6676. };
  6677. /**
  6678. * Returns the value itself if it's between min and max.
  6679. * Returns min if the value is lower than min.
  6680. * Returns max if the value is greater than max.
  6681. */
  6682. Scalar.Clamp = function (value, min, max) {
  6683. if (min === void 0) { min = 0; }
  6684. if (max === void 0) { max = 1; }
  6685. return Math.min(max, Math.max(min, value));
  6686. };
  6687. /**
  6688. * Returns the log2 of value.
  6689. */
  6690. Scalar.Log2 = function (value) {
  6691. return Math.log(value) * Math.LOG2E;
  6692. };
  6693. /**
  6694. * Loops the value, so that it is never larger than length and never smaller than 0.
  6695. *
  6696. * This is similar to the modulo operator but it works with floating point numbers.
  6697. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6698. * With t = 5 and length = 2.5, the result would be 0.0.
  6699. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6700. */
  6701. Scalar.Repeat = function (value, length) {
  6702. return value - Math.floor(value / length) * length;
  6703. };
  6704. /**
  6705. * Normalize the value between 0.0 and 1.0 using min and max values
  6706. */
  6707. Scalar.Normalize = function (value, min, max) {
  6708. return (value - min) / (max - min);
  6709. };
  6710. /**
  6711. * Denormalize the value from 0.0 and 1.0 using min and max values
  6712. */
  6713. Scalar.Denormalize = function (normalized, min, max) {
  6714. return (normalized * (max - min) + min);
  6715. };
  6716. /**
  6717. * Calculates the shortest difference between two given angles given in degrees.
  6718. */
  6719. Scalar.DeltaAngle = function (current, target) {
  6720. var num = Scalar.Repeat(target - current, 360.0);
  6721. if (num > 180.0) {
  6722. num -= 360.0;
  6723. }
  6724. return num;
  6725. };
  6726. /**
  6727. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6728. *
  6729. * The returned value will move back and forth between 0 and length
  6730. */
  6731. Scalar.PingPong = function (tx, length) {
  6732. var t = Scalar.Repeat(tx, length * 2.0);
  6733. return length - Math.abs(t - length);
  6734. };
  6735. /**
  6736. * Interpolates between min and max with smoothing at the limits.
  6737. *
  6738. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6739. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6740. */
  6741. Scalar.SmoothStep = function (from, to, tx) {
  6742. var t = Scalar.Clamp(tx);
  6743. t = -2.0 * t * t * t + 3.0 * t * t;
  6744. return to * t + from * (1.0 - t);
  6745. };
  6746. /**
  6747. * Moves a value current towards target.
  6748. *
  6749. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6750. * Negative values of maxDelta pushes the value away from target.
  6751. */
  6752. Scalar.MoveTowards = function (current, target, maxDelta) {
  6753. var result = 0;
  6754. if (Math.abs(target - current) <= maxDelta) {
  6755. result = target;
  6756. }
  6757. else {
  6758. result = current + Scalar.Sign(target - current) * maxDelta;
  6759. }
  6760. return result;
  6761. };
  6762. /**
  6763. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6764. *
  6765. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6766. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6767. */
  6768. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6769. var num = Scalar.DeltaAngle(current, target);
  6770. var result = 0;
  6771. if (-maxDelta < num && num < maxDelta) {
  6772. result = target;
  6773. }
  6774. else {
  6775. target = current + num;
  6776. result = Scalar.MoveTowards(current, target, maxDelta);
  6777. }
  6778. return result;
  6779. };
  6780. /**
  6781. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6782. */
  6783. Scalar.Lerp = function (start, end, amount) {
  6784. return start + ((end - start) * amount);
  6785. };
  6786. /**
  6787. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6788. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6789. */
  6790. Scalar.LerpAngle = function (start, end, amount) {
  6791. var num = Scalar.Repeat(end - start, 360.0);
  6792. if (num > 180.0) {
  6793. num -= 360.0;
  6794. }
  6795. return start + num * Scalar.Clamp(amount);
  6796. };
  6797. /**
  6798. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6799. */
  6800. Scalar.InverseLerp = function (a, b, value) {
  6801. var result = 0;
  6802. if (a != b) {
  6803. result = Scalar.Clamp((value - a) / (b - a));
  6804. }
  6805. else {
  6806. result = 0.0;
  6807. }
  6808. return result;
  6809. };
  6810. /**
  6811. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6812. */
  6813. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6814. var squared = amount * amount;
  6815. var cubed = amount * squared;
  6816. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6817. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6818. var part3 = (cubed - (2.0 * squared)) + amount;
  6819. var part4 = cubed - squared;
  6820. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6821. };
  6822. /**
  6823. * Returns a random float number between and min and max values
  6824. */
  6825. Scalar.RandomRange = function (min, max) {
  6826. if (min === max)
  6827. return min;
  6828. return ((Math.random() * (max - min)) + min);
  6829. };
  6830. /**
  6831. * This function returns percentage of a number in a given range.
  6832. *
  6833. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6834. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6835. */
  6836. Scalar.RangeToPercent = function (number, min, max) {
  6837. return ((number - min) / (max - min));
  6838. };
  6839. /**
  6840. * This function returns number that corresponds to the percentage in a given range.
  6841. *
  6842. * PercentToRange(0.34,0,100) will return 34.
  6843. */
  6844. Scalar.PercentToRange = function (percent, min, max) {
  6845. return ((max - min) * percent + min);
  6846. };
  6847. /**
  6848. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6849. * @param angle The angle to normalize in radian.
  6850. * @return The converted angle.
  6851. */
  6852. Scalar.NormalizeRadians = function (angle) {
  6853. // More precise but slower version kept for reference.
  6854. // angle = angle % Tools.TwoPi;
  6855. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6856. //if (angle > Math.PI) {
  6857. // angle -= Tools.TwoPi;
  6858. //}
  6859. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6860. return angle;
  6861. };
  6862. /**
  6863. * Two pi constants convenient for computation.
  6864. */
  6865. Scalar.TwoPi = Math.PI * 2;
  6866. return Scalar;
  6867. }());
  6868. BABYLON.Scalar = Scalar;
  6869. })(BABYLON || (BABYLON = {}));
  6870. //# sourceMappingURL=babylon.math.scalar.js.map
  6871. //# sourceMappingURL=babylon.mixins.js.map
  6872. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6873. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6874. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6875. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6876. //# sourceMappingURL=babylon.webgl2.js.map
  6877. var BABYLON;
  6878. (function (BABYLON) {
  6879. var __decoratorInitialStore = {};
  6880. var __mergedStore = {};
  6881. var _copySource = function (creationFunction, source, instanciate) {
  6882. var destination = creationFunction();
  6883. // Tags
  6884. if (BABYLON.Tags) {
  6885. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6886. }
  6887. var classStore = getMergedStore(destination);
  6888. // Properties
  6889. for (var property in classStore) {
  6890. var propertyDescriptor = classStore[property];
  6891. var sourceProperty = source[property];
  6892. var propertyType = propertyDescriptor.type;
  6893. if (sourceProperty !== undefined && sourceProperty !== null) {
  6894. switch (propertyType) {
  6895. case 0: // Value
  6896. case 6:// Mesh reference
  6897. destination[property] = sourceProperty;
  6898. break;
  6899. case 1:// Texture
  6900. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6901. break;
  6902. case 2: // Color3
  6903. case 3: // FresnelParameters
  6904. case 4: // Vector2
  6905. case 5: // Vector3
  6906. case 7: // Color Curves
  6907. case 10:// Quaternion
  6908. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6909. break;
  6910. }
  6911. }
  6912. }
  6913. return destination;
  6914. };
  6915. function getDirectStore(target) {
  6916. var classKey = target.getClassName();
  6917. if (!__decoratorInitialStore[classKey]) {
  6918. __decoratorInitialStore[classKey] = {};
  6919. }
  6920. return __decoratorInitialStore[classKey];
  6921. }
  6922. /**
  6923. * Return the list of properties flagged as serializable
  6924. * @param target: host object
  6925. */
  6926. function getMergedStore(target) {
  6927. var classKey = target.getClassName();
  6928. if (__mergedStore[classKey]) {
  6929. return __mergedStore[classKey];
  6930. }
  6931. __mergedStore[classKey] = {};
  6932. var store = __mergedStore[classKey];
  6933. var currentTarget = target;
  6934. var currentKey = classKey;
  6935. while (currentKey) {
  6936. var initialStore = __decoratorInitialStore[currentKey];
  6937. for (var property in initialStore) {
  6938. store[property] = initialStore[property];
  6939. }
  6940. var parent_1 = void 0;
  6941. var done = false;
  6942. do {
  6943. parent_1 = Object.getPrototypeOf(currentTarget);
  6944. if (!parent_1.getClassName) {
  6945. done = true;
  6946. break;
  6947. }
  6948. if (parent_1.getClassName() !== currentKey) {
  6949. break;
  6950. }
  6951. currentTarget = parent_1;
  6952. } while (parent_1);
  6953. if (done) {
  6954. break;
  6955. }
  6956. currentKey = parent_1.getClassName();
  6957. currentTarget = parent_1;
  6958. }
  6959. return store;
  6960. }
  6961. function generateSerializableMember(type, sourceName) {
  6962. return function (target, propertyKey) {
  6963. var classStore = getDirectStore(target);
  6964. if (!classStore[propertyKey]) {
  6965. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6966. }
  6967. };
  6968. }
  6969. function generateExpandMember(setCallback, targetKey) {
  6970. if (targetKey === void 0) { targetKey = null; }
  6971. return function (target, propertyKey) {
  6972. var key = targetKey || ("_" + propertyKey);
  6973. Object.defineProperty(target, propertyKey, {
  6974. get: function () {
  6975. return this[key];
  6976. },
  6977. set: function (value) {
  6978. if (this[key] === value) {
  6979. return;
  6980. }
  6981. this[key] = value;
  6982. target[setCallback].apply(this);
  6983. },
  6984. enumerable: true,
  6985. configurable: true
  6986. });
  6987. };
  6988. }
  6989. function expandToProperty(callback, targetKey) {
  6990. if (targetKey === void 0) { targetKey = null; }
  6991. return generateExpandMember(callback, targetKey);
  6992. }
  6993. BABYLON.expandToProperty = expandToProperty;
  6994. function serialize(sourceName) {
  6995. return generateSerializableMember(0, sourceName); // value member
  6996. }
  6997. BABYLON.serialize = serialize;
  6998. function serializeAsTexture(sourceName) {
  6999. return generateSerializableMember(1, sourceName); // texture member
  7000. }
  7001. BABYLON.serializeAsTexture = serializeAsTexture;
  7002. function serializeAsColor3(sourceName) {
  7003. return generateSerializableMember(2, sourceName); // color3 member
  7004. }
  7005. BABYLON.serializeAsColor3 = serializeAsColor3;
  7006. function serializeAsFresnelParameters(sourceName) {
  7007. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7008. }
  7009. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7010. function serializeAsVector2(sourceName) {
  7011. return generateSerializableMember(4, sourceName); // vector2 member
  7012. }
  7013. BABYLON.serializeAsVector2 = serializeAsVector2;
  7014. function serializeAsVector3(sourceName) {
  7015. return generateSerializableMember(5, sourceName); // vector3 member
  7016. }
  7017. BABYLON.serializeAsVector3 = serializeAsVector3;
  7018. function serializeAsMeshReference(sourceName) {
  7019. return generateSerializableMember(6, sourceName); // mesh reference member
  7020. }
  7021. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7022. function serializeAsColorCurves(sourceName) {
  7023. return generateSerializableMember(7, sourceName); // color curves
  7024. }
  7025. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7026. function serializeAsColor4(sourceName) {
  7027. return generateSerializableMember(8, sourceName); // color 4
  7028. }
  7029. BABYLON.serializeAsColor4 = serializeAsColor4;
  7030. function serializeAsImageProcessingConfiguration(sourceName) {
  7031. return generateSerializableMember(9, sourceName); // image processing
  7032. }
  7033. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7034. function serializeAsQuaternion(sourceName) {
  7035. return generateSerializableMember(10, sourceName); // quaternion member
  7036. }
  7037. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7038. var SerializationHelper = /** @class */ (function () {
  7039. function SerializationHelper() {
  7040. }
  7041. SerializationHelper.Serialize = function (entity, serializationObject) {
  7042. if (!serializationObject) {
  7043. serializationObject = {};
  7044. }
  7045. // Tags
  7046. if (BABYLON.Tags) {
  7047. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7048. }
  7049. var serializedProperties = getMergedStore(entity);
  7050. // Properties
  7051. for (var property in serializedProperties) {
  7052. var propertyDescriptor = serializedProperties[property];
  7053. var targetPropertyName = propertyDescriptor.sourceName || property;
  7054. var propertyType = propertyDescriptor.type;
  7055. var sourceProperty = entity[property];
  7056. if (sourceProperty !== undefined && sourceProperty !== null) {
  7057. switch (propertyType) {
  7058. case 0:// Value
  7059. serializationObject[targetPropertyName] = sourceProperty;
  7060. break;
  7061. case 1:// Texture
  7062. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7063. break;
  7064. case 2:// Color3
  7065. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7066. break;
  7067. case 3:// FresnelParameters
  7068. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7069. break;
  7070. case 4:// Vector2
  7071. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7072. break;
  7073. case 5:// Vector3
  7074. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7075. break;
  7076. case 6:// Mesh reference
  7077. serializationObject[targetPropertyName] = sourceProperty.id;
  7078. break;
  7079. case 7:// Color Curves
  7080. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7081. break;
  7082. case 8:// Color 4
  7083. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7084. break;
  7085. case 9:// Image Processing
  7086. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7087. break;
  7088. }
  7089. }
  7090. }
  7091. return serializationObject;
  7092. };
  7093. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7094. if (rootUrl === void 0) { rootUrl = null; }
  7095. var destination = creationFunction();
  7096. if (!rootUrl) {
  7097. rootUrl = "";
  7098. }
  7099. // Tags
  7100. if (BABYLON.Tags) {
  7101. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7102. }
  7103. var classStore = getMergedStore(destination);
  7104. // Properties
  7105. for (var property in classStore) {
  7106. var propertyDescriptor = classStore[property];
  7107. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7108. var propertyType = propertyDescriptor.type;
  7109. if (sourceProperty !== undefined && sourceProperty !== null) {
  7110. var dest = destination;
  7111. switch (propertyType) {
  7112. case 0:// Value
  7113. dest[property] = sourceProperty;
  7114. break;
  7115. case 1:// Texture
  7116. if (scene) {
  7117. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7118. }
  7119. break;
  7120. case 2:// Color3
  7121. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7122. break;
  7123. case 3:// FresnelParameters
  7124. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7125. break;
  7126. case 4:// Vector2
  7127. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7128. break;
  7129. case 5:// Vector3
  7130. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7131. break;
  7132. case 6:// Mesh reference
  7133. if (scene) {
  7134. dest[property] = scene.getLastMeshByID(sourceProperty);
  7135. }
  7136. break;
  7137. case 7:// Color Curves
  7138. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7139. break;
  7140. case 8:// Color 4
  7141. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7142. break;
  7143. case 9:// Image Processing
  7144. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7145. break;
  7146. }
  7147. }
  7148. }
  7149. return destination;
  7150. };
  7151. SerializationHelper.Clone = function (creationFunction, source) {
  7152. return _copySource(creationFunction, source, false);
  7153. };
  7154. SerializationHelper.Instanciate = function (creationFunction, source) {
  7155. return _copySource(creationFunction, source, true);
  7156. };
  7157. return SerializationHelper;
  7158. }());
  7159. BABYLON.SerializationHelper = SerializationHelper;
  7160. })(BABYLON || (BABYLON = {}));
  7161. //# sourceMappingURL=babylon.decorators.js.map
  7162. var BABYLON;
  7163. (function (BABYLON) {
  7164. /**
  7165. * Wrapper class for promise with external resolve and reject.
  7166. */
  7167. var Deferred = /** @class */ (function () {
  7168. /**
  7169. * Constructor for this deferred object.
  7170. */
  7171. function Deferred() {
  7172. var _this = this;
  7173. this.promise = new Promise(function (resolve, reject) {
  7174. _this._resolve = resolve;
  7175. _this._reject = reject;
  7176. });
  7177. }
  7178. Object.defineProperty(Deferred.prototype, "resolve", {
  7179. /**
  7180. * The resolve method of the promise associated with this deferred object.
  7181. */
  7182. get: function () {
  7183. return this._resolve;
  7184. },
  7185. enumerable: true,
  7186. configurable: true
  7187. });
  7188. Object.defineProperty(Deferred.prototype, "reject", {
  7189. /**
  7190. * The reject method of the promise associated with this deferred object.
  7191. */
  7192. get: function () {
  7193. return this._reject;
  7194. },
  7195. enumerable: true,
  7196. configurable: true
  7197. });
  7198. return Deferred;
  7199. }());
  7200. BABYLON.Deferred = Deferred;
  7201. })(BABYLON || (BABYLON = {}));
  7202. //# sourceMappingURL=babylon.deferred.js.map
  7203. var BABYLON;
  7204. (function (BABYLON) {
  7205. /**
  7206. * A class serves as a medium between the observable and its observers
  7207. */
  7208. var EventState = /** @class */ (function () {
  7209. /**
  7210. * Create a new EventState
  7211. * @param mask defines the mask associated with this state
  7212. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7213. * @param target defines the original target of the state
  7214. * @param currentTarget defines the current target of the state
  7215. */
  7216. function EventState(mask, skipNextObservers, target, currentTarget) {
  7217. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7218. this.initalize(mask, skipNextObservers, target, currentTarget);
  7219. }
  7220. /**
  7221. * Initialize the current event state
  7222. * @param mask defines the mask associated with this state
  7223. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7224. * @param target defines the original target of the state
  7225. * @param currentTarget defines the current target of the state
  7226. * @returns the current event state
  7227. */
  7228. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7229. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7230. this.mask = mask;
  7231. this.skipNextObservers = skipNextObservers;
  7232. this.target = target;
  7233. this.currentTarget = currentTarget;
  7234. return this;
  7235. };
  7236. return EventState;
  7237. }());
  7238. BABYLON.EventState = EventState;
  7239. /**
  7240. * Represent an Observer registered to a given Observable object.
  7241. */
  7242. var Observer = /** @class */ (function () {
  7243. /**
  7244. * Creates a new observer
  7245. * @param callback defines the callback to call when the observer is notified
  7246. * @param mask defines the mask of the observer (used to filter notifications)
  7247. * @param scope defines the current scope used to restore the JS context
  7248. */
  7249. function Observer(
  7250. /**
  7251. * Defines the callback to call when the observer is notified
  7252. */
  7253. callback,
  7254. /**
  7255. * Defines the mask of the observer (used to filter notifications)
  7256. */
  7257. mask,
  7258. /**
  7259. * Defines the current scope used to restore the JS context
  7260. */
  7261. scope) {
  7262. if (scope === void 0) { scope = null; }
  7263. this.callback = callback;
  7264. this.mask = mask;
  7265. this.scope = scope;
  7266. /** @ignore */
  7267. this._willBeUnregistered = false;
  7268. /**
  7269. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7270. */
  7271. this.unregisterOnNextCall = false;
  7272. }
  7273. return Observer;
  7274. }());
  7275. BABYLON.Observer = Observer;
  7276. /**
  7277. * Represent a list of observers registered to multiple Observables object.
  7278. */
  7279. var MultiObserver = /** @class */ (function () {
  7280. function MultiObserver() {
  7281. }
  7282. /**
  7283. * Release associated resources
  7284. */
  7285. MultiObserver.prototype.dispose = function () {
  7286. if (this._observers && this._observables) {
  7287. for (var index = 0; index < this._observers.length; index++) {
  7288. this._observables[index].remove(this._observers[index]);
  7289. }
  7290. }
  7291. this._observers = null;
  7292. this._observables = null;
  7293. };
  7294. /**
  7295. * Raise a callback when one of the observable will notify
  7296. * @param observables defines a list of observables to watch
  7297. * @param callback defines the callback to call on notification
  7298. * @param mask defines the mask used to filter notifications
  7299. * @param scope defines the current scope used to restore the JS context
  7300. * @returns the new MultiObserver
  7301. */
  7302. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7303. if (mask === void 0) { mask = -1; }
  7304. if (scope === void 0) { scope = null; }
  7305. var result = new MultiObserver();
  7306. result._observers = new Array();
  7307. result._observables = observables;
  7308. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7309. var observable = observables_1[_i];
  7310. var observer = observable.add(callback, mask, false, scope);
  7311. if (observer) {
  7312. result._observers.push(observer);
  7313. }
  7314. }
  7315. return result;
  7316. };
  7317. return MultiObserver;
  7318. }());
  7319. BABYLON.MultiObserver = MultiObserver;
  7320. /**
  7321. * The Observable class is a simple implementation of the Observable pattern.
  7322. * 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.
  7323. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7324. * 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).
  7325. * 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.
  7326. */
  7327. var Observable = /** @class */ (function () {
  7328. /**
  7329. * Creates a new observable
  7330. * @param onObserverAdded defines a callback to call when a new observer is added
  7331. */
  7332. function Observable(onObserverAdded) {
  7333. this._observers = new Array();
  7334. this._eventState = new EventState(0);
  7335. if (onObserverAdded) {
  7336. this._onObserverAdded = onObserverAdded;
  7337. }
  7338. }
  7339. /**
  7340. * Create a new Observer with the specified callback
  7341. * @param callback the callback that will be executed for that Observer
  7342. * @param mask the mask used to filter observers
  7343. * @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.
  7344. * @param scope optional scope for the callback to be called from
  7345. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7346. * @returns the new observer created for the callback
  7347. */
  7348. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7349. if (mask === void 0) { mask = -1; }
  7350. if (insertFirst === void 0) { insertFirst = false; }
  7351. if (scope === void 0) { scope = null; }
  7352. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7353. if (!callback) {
  7354. return null;
  7355. }
  7356. var observer = new Observer(callback, mask, scope);
  7357. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7358. if (insertFirst) {
  7359. this._observers.unshift(observer);
  7360. }
  7361. else {
  7362. this._observers.push(observer);
  7363. }
  7364. if (this._onObserverAdded) {
  7365. this._onObserverAdded(observer);
  7366. }
  7367. return observer;
  7368. };
  7369. /**
  7370. * Remove an Observer from the Observable object
  7371. * @param observer the instance of the Observer to remove
  7372. * @returns false if it doesn't belong to this Observable
  7373. */
  7374. Observable.prototype.remove = function (observer) {
  7375. if (!observer) {
  7376. return false;
  7377. }
  7378. var index = this._observers.indexOf(observer);
  7379. if (index !== -1) {
  7380. this._observers.splice(index, 1);
  7381. return true;
  7382. }
  7383. return false;
  7384. };
  7385. /**
  7386. * Remove a callback from the Observable object
  7387. * @param callback the callback to remove
  7388. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7389. * @returns false if it doesn't belong to this Observable
  7390. */
  7391. Observable.prototype.removeCallback = function (callback, scope) {
  7392. for (var index = 0; index < this._observers.length; index++) {
  7393. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7394. this._observers.splice(index, 1);
  7395. return true;
  7396. }
  7397. }
  7398. return false;
  7399. };
  7400. Observable.prototype._deferUnregister = function (observer) {
  7401. var _this = this;
  7402. observer.unregisterOnNextCall = false;
  7403. observer._willBeUnregistered = true;
  7404. BABYLON.Tools.SetImmediate(function () {
  7405. _this.remove(observer);
  7406. });
  7407. };
  7408. /**
  7409. * Notify all Observers by calling their respective callback with the given data
  7410. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7411. * @param eventData defines the data to send to all observers
  7412. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7413. * @param target defines the original target of the state
  7414. * @param currentTarget defines the current target of the state
  7415. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7416. */
  7417. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7418. if (mask === void 0) { mask = -1; }
  7419. if (!this._observers.length) {
  7420. return true;
  7421. }
  7422. var state = this._eventState;
  7423. state.mask = mask;
  7424. state.target = target;
  7425. state.currentTarget = currentTarget;
  7426. state.skipNextObservers = false;
  7427. state.lastReturnValue = eventData;
  7428. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7429. var obs = _a[_i];
  7430. if (obs._willBeUnregistered) {
  7431. continue;
  7432. }
  7433. if (obs.mask & mask) {
  7434. if (obs.scope) {
  7435. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7436. }
  7437. else {
  7438. state.lastReturnValue = obs.callback(eventData, state);
  7439. }
  7440. if (obs.unregisterOnNextCall) {
  7441. this._deferUnregister(obs);
  7442. }
  7443. }
  7444. if (state.skipNextObservers) {
  7445. return false;
  7446. }
  7447. }
  7448. return true;
  7449. };
  7450. /**
  7451. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7452. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7453. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7454. * and it is crucial that all callbacks will be executed.
  7455. * The order of the callbacks is kept, callbacks are not executed parallel.
  7456. *
  7457. * @param eventData The data to be sent to each callback
  7458. * @param mask is used to filter observers defaults to -1
  7459. * @param target defines the callback target (see EventState)
  7460. * @param currentTarget defines he current object in the bubbling phase
  7461. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7462. */
  7463. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7464. var _this = this;
  7465. if (mask === void 0) { mask = -1; }
  7466. // create an empty promise
  7467. var p = Promise.resolve(eventData);
  7468. // no observers? return this promise.
  7469. if (!this._observers.length) {
  7470. return p;
  7471. }
  7472. var state = this._eventState;
  7473. state.mask = mask;
  7474. state.target = target;
  7475. state.currentTarget = currentTarget;
  7476. state.skipNextObservers = false;
  7477. // execute one callback after another (not using Promise.all, the order is important)
  7478. this._observers.forEach(function (obs) {
  7479. if (state.skipNextObservers) {
  7480. return;
  7481. }
  7482. if (obs._willBeUnregistered) {
  7483. return;
  7484. }
  7485. if (obs.mask & mask) {
  7486. if (obs.scope) {
  7487. p = p.then(function (lastReturnedValue) {
  7488. state.lastReturnValue = lastReturnedValue;
  7489. return obs.callback.apply(obs.scope, [eventData, state]);
  7490. });
  7491. }
  7492. else {
  7493. p = p.then(function (lastReturnedValue) {
  7494. state.lastReturnValue = lastReturnedValue;
  7495. return obs.callback(eventData, state);
  7496. });
  7497. }
  7498. if (obs.unregisterOnNextCall) {
  7499. _this._deferUnregister(obs);
  7500. }
  7501. }
  7502. });
  7503. // return the eventData
  7504. return p.then(function () { return eventData; });
  7505. };
  7506. /**
  7507. * Notify a specific observer
  7508. * @param observer defines the observer to notify
  7509. * @param eventData defines the data to be sent to each callback
  7510. * @param mask is used to filter observers defaults to -1
  7511. */
  7512. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7513. if (mask === void 0) { mask = -1; }
  7514. var state = this._eventState;
  7515. state.mask = mask;
  7516. state.skipNextObservers = false;
  7517. observer.callback(eventData, state);
  7518. };
  7519. /**
  7520. * Gets a boolean indicating if the observable has at least one observer
  7521. * @returns true is the Observable has at least one Observer registered
  7522. */
  7523. Observable.prototype.hasObservers = function () {
  7524. return this._observers.length > 0;
  7525. };
  7526. /**
  7527. * Clear the list of observers
  7528. */
  7529. Observable.prototype.clear = function () {
  7530. this._observers = new Array();
  7531. this._onObserverAdded = null;
  7532. };
  7533. /**
  7534. * Clone the current observable
  7535. * @returns a new observable
  7536. */
  7537. Observable.prototype.clone = function () {
  7538. var result = new Observable();
  7539. result._observers = this._observers.slice(0);
  7540. return result;
  7541. };
  7542. /**
  7543. * Does this observable handles observer registered with a given mask
  7544. * @param mask defines the mask to be tested
  7545. * @return whether or not one observer registered with the given mask is handeled
  7546. **/
  7547. Observable.prototype.hasSpecificMask = function (mask) {
  7548. if (mask === void 0) { mask = -1; }
  7549. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7550. var obs = _a[_i];
  7551. if (obs.mask & mask || obs.mask === mask) {
  7552. return true;
  7553. }
  7554. }
  7555. return false;
  7556. };
  7557. return Observable;
  7558. }());
  7559. BABYLON.Observable = Observable;
  7560. })(BABYLON || (BABYLON = {}));
  7561. //# sourceMappingURL=babylon.observable.js.map
  7562. var BABYLON;
  7563. (function (BABYLON) {
  7564. var SmartArray = /** @class */ (function () {
  7565. function SmartArray(capacity) {
  7566. this.length = 0;
  7567. this.data = new Array(capacity);
  7568. this._id = SmartArray._GlobalId++;
  7569. }
  7570. SmartArray.prototype.push = function (value) {
  7571. this.data[this.length++] = value;
  7572. if (this.length > this.data.length) {
  7573. this.data.length *= 2;
  7574. }
  7575. };
  7576. SmartArray.prototype.forEach = function (func) {
  7577. for (var index = 0; index < this.length; index++) {
  7578. func(this.data[index]);
  7579. }
  7580. };
  7581. SmartArray.prototype.sort = function (compareFn) {
  7582. this.data.sort(compareFn);
  7583. };
  7584. SmartArray.prototype.reset = function () {
  7585. this.length = 0;
  7586. };
  7587. SmartArray.prototype.dispose = function () {
  7588. this.reset();
  7589. if (this.data) {
  7590. this.data.length = 0;
  7591. this.data = [];
  7592. }
  7593. };
  7594. SmartArray.prototype.concat = function (array) {
  7595. if (array.length === 0) {
  7596. return;
  7597. }
  7598. if (this.length + array.length > this.data.length) {
  7599. this.data.length = (this.length + array.length) * 2;
  7600. }
  7601. for (var index = 0; index < array.length; index++) {
  7602. this.data[this.length++] = (array.data || array)[index];
  7603. }
  7604. };
  7605. SmartArray.prototype.indexOf = function (value) {
  7606. var position = this.data.indexOf(value);
  7607. if (position >= this.length) {
  7608. return -1;
  7609. }
  7610. return position;
  7611. };
  7612. SmartArray.prototype.contains = function (value) {
  7613. return this.data.indexOf(value) !== -1;
  7614. };
  7615. // Statics
  7616. SmartArray._GlobalId = 0;
  7617. return SmartArray;
  7618. }());
  7619. BABYLON.SmartArray = SmartArray;
  7620. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7621. __extends(SmartArrayNoDuplicate, _super);
  7622. function SmartArrayNoDuplicate() {
  7623. var _this = _super !== null && _super.apply(this, arguments) || this;
  7624. _this._duplicateId = 0;
  7625. return _this;
  7626. }
  7627. SmartArrayNoDuplicate.prototype.push = function (value) {
  7628. _super.prototype.push.call(this, value);
  7629. if (!value.__smartArrayFlags) {
  7630. value.__smartArrayFlags = {};
  7631. }
  7632. value.__smartArrayFlags[this._id] = this._duplicateId;
  7633. };
  7634. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7635. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7636. return false;
  7637. }
  7638. this.push(value);
  7639. return true;
  7640. };
  7641. SmartArrayNoDuplicate.prototype.reset = function () {
  7642. _super.prototype.reset.call(this);
  7643. this._duplicateId++;
  7644. };
  7645. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7646. if (array.length === 0) {
  7647. return;
  7648. }
  7649. if (this.length + array.length > this.data.length) {
  7650. this.data.length = (this.length + array.length) * 2;
  7651. }
  7652. for (var index = 0; index < array.length; index++) {
  7653. var item = (array.data || array)[index];
  7654. this.pushNoDuplicate(item);
  7655. }
  7656. };
  7657. return SmartArrayNoDuplicate;
  7658. }(SmartArray));
  7659. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7660. })(BABYLON || (BABYLON = {}));
  7661. //# sourceMappingURL=babylon.smartArray.js.map
  7662. var BABYLON;
  7663. (function (BABYLON) {
  7664. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7665. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7666. var LoadFileError = /** @class */ (function (_super) {
  7667. __extends(LoadFileError, _super);
  7668. function LoadFileError(message, request) {
  7669. var _this = _super.call(this, message) || this;
  7670. _this.request = request;
  7671. _this.name = "LoadFileError";
  7672. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7673. return _this;
  7674. }
  7675. // Polyfill for Object.setPrototypeOf if necessary.
  7676. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7677. return LoadFileError;
  7678. }(Error));
  7679. BABYLON.LoadFileError = LoadFileError;
  7680. var RetryStrategy = /** @class */ (function () {
  7681. function RetryStrategy() {
  7682. }
  7683. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7684. if (maxRetries === void 0) { maxRetries = 3; }
  7685. if (baseInterval === void 0) { baseInterval = 500; }
  7686. return function (url, request, retryIndex) {
  7687. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7688. return -1;
  7689. }
  7690. return Math.pow(2, retryIndex) * baseInterval;
  7691. };
  7692. };
  7693. return RetryStrategy;
  7694. }());
  7695. BABYLON.RetryStrategy = RetryStrategy;
  7696. // Screenshots
  7697. var screenshotCanvas;
  7698. var cloneValue = function (source, destinationObject) {
  7699. if (!source)
  7700. return null;
  7701. if (source instanceof BABYLON.Mesh) {
  7702. return null;
  7703. }
  7704. if (source instanceof BABYLON.SubMesh) {
  7705. return source.clone(destinationObject);
  7706. }
  7707. else if (source.clone) {
  7708. return source.clone();
  7709. }
  7710. return null;
  7711. };
  7712. var Tools = /** @class */ (function () {
  7713. function Tools() {
  7714. }
  7715. /**
  7716. * Interpolates between a and b via alpha
  7717. * @param a The lower value (returned when alpha = 0)
  7718. * @param b The upper value (returned when alpha = 1)
  7719. * @param alpha The interpolation-factor
  7720. * @return The mixed value
  7721. */
  7722. Tools.Mix = function (a, b, alpha) {
  7723. return a * (1 - alpha) + b * alpha;
  7724. };
  7725. Tools.Instantiate = function (className) {
  7726. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7727. return Tools.RegisteredExternalClasses[className];
  7728. }
  7729. var arr = className.split(".");
  7730. var fn = (window || this);
  7731. for (var i = 0, len = arr.length; i < len; i++) {
  7732. fn = fn[arr[i]];
  7733. }
  7734. if (typeof fn !== "function") {
  7735. return null;
  7736. }
  7737. return fn;
  7738. };
  7739. /**
  7740. * Provides a slice function that will work even on IE
  7741. * @param data defines the array to slice
  7742. * @returns the new sliced array
  7743. */
  7744. Tools.Slice = function (data) {
  7745. if (data.slice) {
  7746. return data.slice();
  7747. }
  7748. return Array.prototype.slice.call(data);
  7749. };
  7750. Tools.SetImmediate = function (action) {
  7751. if (window.setImmediate) {
  7752. window.setImmediate(action);
  7753. }
  7754. else {
  7755. setTimeout(action, 1);
  7756. }
  7757. };
  7758. Tools.IsExponentOfTwo = function (value) {
  7759. var count = 1;
  7760. do {
  7761. count *= 2;
  7762. } while (count < value);
  7763. return count === value;
  7764. };
  7765. /**
  7766. * Find the next highest power of two.
  7767. * @param x Number to start search from.
  7768. * @return Next highest power of two.
  7769. */
  7770. Tools.CeilingPOT = function (x) {
  7771. x--;
  7772. x |= x >> 1;
  7773. x |= x >> 2;
  7774. x |= x >> 4;
  7775. x |= x >> 8;
  7776. x |= x >> 16;
  7777. x++;
  7778. return x;
  7779. };
  7780. /**
  7781. * Find the next lowest power of two.
  7782. * @param x Number to start search from.
  7783. * @return Next lowest power of two.
  7784. */
  7785. Tools.FloorPOT = function (x) {
  7786. x = x | (x >> 1);
  7787. x = x | (x >> 2);
  7788. x = x | (x >> 4);
  7789. x = x | (x >> 8);
  7790. x = x | (x >> 16);
  7791. return x - (x >> 1);
  7792. };
  7793. /**
  7794. * Find the nearest power of two.
  7795. * @param x Number to start search from.
  7796. * @return Next nearest power of two.
  7797. */
  7798. Tools.NearestPOT = function (x) {
  7799. var c = Tools.CeilingPOT(x);
  7800. var f = Tools.FloorPOT(x);
  7801. return (c - x) > (x - f) ? f : c;
  7802. };
  7803. Tools.GetExponentOfTwo = function (value, max, mode) {
  7804. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7805. var pot;
  7806. switch (mode) {
  7807. case BABYLON.Engine.SCALEMODE_FLOOR:
  7808. pot = Tools.FloorPOT(value);
  7809. break;
  7810. case BABYLON.Engine.SCALEMODE_NEAREST:
  7811. pot = Tools.NearestPOT(value);
  7812. break;
  7813. case BABYLON.Engine.SCALEMODE_CEILING:
  7814. default:
  7815. pot = Tools.CeilingPOT(value);
  7816. break;
  7817. }
  7818. return Math.min(pot, max);
  7819. };
  7820. Tools.GetFilename = function (path) {
  7821. var index = path.lastIndexOf("/");
  7822. if (index < 0)
  7823. return path;
  7824. return path.substring(index + 1);
  7825. };
  7826. /**
  7827. * Extracts the "folder" part of a path (everything before the filename).
  7828. * @param uri The URI to extract the info from
  7829. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7830. * @returns The "folder" part of the path
  7831. */
  7832. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7833. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7834. var index = uri.lastIndexOf("/");
  7835. if (index < 0) {
  7836. if (returnUnchangedIfNoSlash) {
  7837. return uri;
  7838. }
  7839. return "";
  7840. }
  7841. return uri.substring(0, index + 1);
  7842. };
  7843. Tools.GetDOMTextContent = function (element) {
  7844. var result = "";
  7845. var child = element.firstChild;
  7846. while (child) {
  7847. if (child.nodeType === 3) {
  7848. result += child.textContent;
  7849. }
  7850. child = child.nextSibling;
  7851. }
  7852. return result;
  7853. };
  7854. Tools.ToDegrees = function (angle) {
  7855. return angle * 180 / Math.PI;
  7856. };
  7857. Tools.ToRadians = function (angle) {
  7858. return angle * Math.PI / 180;
  7859. };
  7860. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7861. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7862. var output = "";
  7863. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7864. var i = 0;
  7865. var bytes = new Uint8Array(buffer);
  7866. while (i < bytes.length) {
  7867. chr1 = bytes[i++];
  7868. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7869. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7870. enc1 = chr1 >> 2;
  7871. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7872. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7873. enc4 = chr3 & 63;
  7874. if (isNaN(chr2)) {
  7875. enc3 = enc4 = 64;
  7876. }
  7877. else if (isNaN(chr3)) {
  7878. enc4 = 64;
  7879. }
  7880. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7881. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7882. }
  7883. return "data:image/png;base64," + output;
  7884. };
  7885. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7886. if (bias === void 0) { bias = null; }
  7887. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7888. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7889. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7890. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7891. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7892. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7893. }
  7894. if (bias) {
  7895. minimum.x -= minimum.x * bias.x + bias.y;
  7896. minimum.y -= minimum.y * bias.x + bias.y;
  7897. minimum.z -= minimum.z * bias.x + bias.y;
  7898. maximum.x += maximum.x * bias.x + bias.y;
  7899. maximum.y += maximum.y * bias.x + bias.y;
  7900. maximum.z += maximum.z * bias.x + bias.y;
  7901. }
  7902. return {
  7903. minimum: minimum,
  7904. maximum: maximum
  7905. };
  7906. };
  7907. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7908. if (bias === void 0) { bias = null; }
  7909. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7910. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7911. if (!stride) {
  7912. stride = 3;
  7913. }
  7914. for (var index = start; index < start + count; index++) {
  7915. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7916. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7917. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7918. }
  7919. if (bias) {
  7920. minimum.x -= minimum.x * bias.x + bias.y;
  7921. minimum.y -= minimum.y * bias.x + bias.y;
  7922. minimum.z -= minimum.z * bias.x + bias.y;
  7923. maximum.x += maximum.x * bias.x + bias.y;
  7924. maximum.y += maximum.y * bias.x + bias.y;
  7925. maximum.z += maximum.z * bias.x + bias.y;
  7926. }
  7927. return {
  7928. minimum: minimum,
  7929. maximum: maximum
  7930. };
  7931. };
  7932. Tools.Vector2ArrayFeeder = function (array) {
  7933. return function (index) {
  7934. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7935. var length = isFloatArray ? array.length / 2 : array.length;
  7936. if (index >= length) {
  7937. return null;
  7938. }
  7939. if (isFloatArray) {
  7940. var fa = array;
  7941. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7942. }
  7943. var a = array;
  7944. return a[index];
  7945. };
  7946. };
  7947. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7948. if (bias === void 0) { bias = null; }
  7949. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7950. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7951. var i = 0;
  7952. var cur = feeder(i++);
  7953. while (cur) {
  7954. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7955. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7956. cur = feeder(i++);
  7957. }
  7958. if (bias) {
  7959. minimum.x -= minimum.x * bias.x + bias.y;
  7960. minimum.y -= minimum.y * bias.x + bias.y;
  7961. maximum.x += maximum.x * bias.x + bias.y;
  7962. maximum.y += maximum.y * bias.x + bias.y;
  7963. }
  7964. return {
  7965. minimum: minimum,
  7966. maximum: maximum
  7967. };
  7968. };
  7969. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7970. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7971. return null;
  7972. return Array.isArray(obj) ? obj : [obj];
  7973. };
  7974. // Misc.
  7975. Tools.GetPointerPrefix = function () {
  7976. var eventPrefix = "pointer";
  7977. // Check if pointer events are supported
  7978. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7979. eventPrefix = "mouse";
  7980. }
  7981. return eventPrefix;
  7982. };
  7983. /**
  7984. * @param func - the function to be called
  7985. * @param requester - the object that will request the next frame. Falls back to window.
  7986. */
  7987. Tools.QueueNewFrame = function (func, requester) {
  7988. if (!Tools.IsWindowObjectExist()) {
  7989. return setTimeout(func, 16);
  7990. }
  7991. if (!requester) {
  7992. requester = window;
  7993. }
  7994. if (requester.requestAnimationFrame) {
  7995. return requester.requestAnimationFrame(func);
  7996. }
  7997. else if (requester.msRequestAnimationFrame) {
  7998. return requester.msRequestAnimationFrame(func);
  7999. }
  8000. else if (requester.webkitRequestAnimationFrame) {
  8001. return requester.webkitRequestAnimationFrame(func);
  8002. }
  8003. else if (requester.mozRequestAnimationFrame) {
  8004. return requester.mozRequestAnimationFrame(func);
  8005. }
  8006. else if (requester.oRequestAnimationFrame) {
  8007. return requester.oRequestAnimationFrame(func);
  8008. }
  8009. else {
  8010. return window.setTimeout(func, 16);
  8011. }
  8012. };
  8013. Tools.RequestFullscreen = function (element) {
  8014. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8015. if (!requestFunction)
  8016. return;
  8017. requestFunction.call(element);
  8018. };
  8019. Tools.ExitFullscreen = function () {
  8020. if (document.exitFullscreen) {
  8021. document.exitFullscreen();
  8022. }
  8023. else if (document.mozCancelFullScreen) {
  8024. document.mozCancelFullScreen();
  8025. }
  8026. else if (document.webkitCancelFullScreen) {
  8027. document.webkitCancelFullScreen();
  8028. }
  8029. else if (document.msCancelFullScreen) {
  8030. document.msCancelFullScreen();
  8031. }
  8032. };
  8033. Tools.SetCorsBehavior = function (url, element) {
  8034. if (url && url.indexOf("data:") === 0) {
  8035. return;
  8036. }
  8037. if (Tools.CorsBehavior) {
  8038. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8039. element.crossOrigin = Tools.CorsBehavior;
  8040. }
  8041. else {
  8042. var result = Tools.CorsBehavior(url);
  8043. if (result) {
  8044. element.crossOrigin = result;
  8045. }
  8046. }
  8047. }
  8048. };
  8049. // External files
  8050. Tools.CleanUrl = function (url) {
  8051. url = url.replace(/#/mg, "%23");
  8052. return url;
  8053. };
  8054. Tools.LoadImage = function (url, onLoad, onError, database) {
  8055. if (url instanceof ArrayBuffer) {
  8056. url = Tools.EncodeArrayBufferTobase64(url);
  8057. }
  8058. url = Tools.CleanUrl(url);
  8059. url = Tools.PreprocessUrl(url);
  8060. var img = new Image();
  8061. Tools.SetCorsBehavior(url, img);
  8062. var loadHandler = function () {
  8063. img.removeEventListener("load", loadHandler);
  8064. img.removeEventListener("error", errorHandler);
  8065. onLoad(img);
  8066. };
  8067. var errorHandler = function (err) {
  8068. img.removeEventListener("load", loadHandler);
  8069. img.removeEventListener("error", errorHandler);
  8070. Tools.Error("Error while trying to load image: " + url);
  8071. if (onError) {
  8072. onError("Error while trying to load image: " + url, err);
  8073. }
  8074. };
  8075. img.addEventListener("load", loadHandler);
  8076. img.addEventListener("error", errorHandler);
  8077. var noIndexedDB = function () {
  8078. img.src = url;
  8079. };
  8080. var loadFromIndexedDB = function () {
  8081. if (database) {
  8082. database.loadImageFromDB(url, img);
  8083. }
  8084. };
  8085. //ANY database to do!
  8086. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8087. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8088. }
  8089. else {
  8090. if (url.indexOf("file:") !== -1) {
  8091. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8092. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8093. try {
  8094. var blobURL;
  8095. try {
  8096. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8097. }
  8098. catch (ex) {
  8099. // Chrome doesn't support oneTimeOnly parameter
  8100. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8101. }
  8102. img.src = blobURL;
  8103. }
  8104. catch (e) {
  8105. img.src = "";
  8106. }
  8107. return img;
  8108. }
  8109. }
  8110. noIndexedDB();
  8111. }
  8112. return img;
  8113. };
  8114. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8115. url = Tools.CleanUrl(url);
  8116. url = Tools.PreprocessUrl(url);
  8117. // If file and file input are set
  8118. if (url.indexOf("file:") !== -1) {
  8119. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8120. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8121. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8122. }
  8123. }
  8124. var loadUrl = Tools.BaseUrl + url;
  8125. var aborted = false;
  8126. var fileRequest = {
  8127. onCompleteObservable: new BABYLON.Observable(),
  8128. abort: function () { return aborted = true; },
  8129. };
  8130. var requestFile = function () {
  8131. var request = new XMLHttpRequest();
  8132. var retryHandle = null;
  8133. fileRequest.abort = function () {
  8134. aborted = true;
  8135. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8136. request.abort();
  8137. }
  8138. if (retryHandle !== null) {
  8139. clearTimeout(retryHandle);
  8140. retryHandle = null;
  8141. }
  8142. };
  8143. var retryLoop = function (retryIndex) {
  8144. request.open('GET', loadUrl, true);
  8145. if (useArrayBuffer) {
  8146. request.responseType = "arraybuffer";
  8147. }
  8148. if (onProgress) {
  8149. request.addEventListener("progress", onProgress);
  8150. }
  8151. var onLoadEnd = function () {
  8152. request.removeEventListener("loadend", onLoadEnd);
  8153. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8154. fileRequest.onCompleteObservable.clear();
  8155. };
  8156. request.addEventListener("loadend", onLoadEnd);
  8157. var onReadyStateChange = function () {
  8158. if (aborted) {
  8159. return;
  8160. }
  8161. // In case of undefined state in some browsers.
  8162. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8163. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8164. request.removeEventListener("readystatechange", onReadyStateChange);
  8165. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8166. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8167. return;
  8168. }
  8169. var retryStrategy = Tools.DefaultRetryStrategy;
  8170. if (retryStrategy) {
  8171. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8172. if (waitTime !== -1) {
  8173. // Prevent the request from completing for retry.
  8174. request.removeEventListener("loadend", onLoadEnd);
  8175. request = new XMLHttpRequest();
  8176. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8177. return;
  8178. }
  8179. }
  8180. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8181. if (onError) {
  8182. onError(request, e);
  8183. }
  8184. else {
  8185. throw e;
  8186. }
  8187. }
  8188. };
  8189. request.addEventListener("readystatechange", onReadyStateChange);
  8190. request.send();
  8191. };
  8192. retryLoop(0);
  8193. };
  8194. // Caching all files
  8195. if (database && database.enableSceneOffline) {
  8196. var noIndexedDB_1 = function () {
  8197. if (!aborted) {
  8198. requestFile();
  8199. }
  8200. };
  8201. var loadFromIndexedDB = function () {
  8202. // TODO: database needs to support aborting and should return a IFileRequest
  8203. if (aborted) {
  8204. return;
  8205. }
  8206. if (database) {
  8207. database.loadFileFromDB(url, function (data) {
  8208. if (!aborted) {
  8209. onSuccess(data);
  8210. }
  8211. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8212. }, onProgress ? function (event) {
  8213. if (!aborted) {
  8214. onProgress(event);
  8215. }
  8216. } : undefined, noIndexedDB_1, useArrayBuffer);
  8217. }
  8218. };
  8219. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8220. }
  8221. else {
  8222. requestFile();
  8223. }
  8224. return fileRequest;
  8225. };
  8226. /**
  8227. * Load a script (identified by an url). When the url returns, the
  8228. * content of this file is added into a new script element, attached to the DOM (body element)
  8229. */
  8230. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8231. var head = document.getElementsByTagName('head')[0];
  8232. var script = document.createElement('script');
  8233. script.type = 'text/javascript';
  8234. script.src = scriptUrl;
  8235. script.onload = function () {
  8236. if (onSuccess) {
  8237. onSuccess();
  8238. }
  8239. };
  8240. script.onerror = function (e) {
  8241. if (onError) {
  8242. onError("Unable to load script", e);
  8243. }
  8244. };
  8245. head.appendChild(script);
  8246. };
  8247. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8248. var reader = new FileReader();
  8249. var request = {
  8250. onCompleteObservable: new BABYLON.Observable(),
  8251. abort: function () { return reader.abort(); },
  8252. };
  8253. reader.onloadend = function (e) {
  8254. request.onCompleteObservable.notifyObservers(request);
  8255. };
  8256. reader.onload = function (e) {
  8257. //target doesn't have result from ts 1.3
  8258. callback(e.target['result']);
  8259. };
  8260. reader.onprogress = progressCallback;
  8261. reader.readAsDataURL(fileToLoad);
  8262. return request;
  8263. };
  8264. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8265. var reader = new FileReader();
  8266. var request = {
  8267. onCompleteObservable: new BABYLON.Observable(),
  8268. abort: function () { return reader.abort(); },
  8269. };
  8270. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8271. reader.onerror = function (e) {
  8272. Tools.Log("Error while reading file: " + fileToLoad.name);
  8273. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8274. };
  8275. reader.onload = function (e) {
  8276. //target doesn't have result from ts 1.3
  8277. callback(e.target['result']);
  8278. };
  8279. if (progressCallBack) {
  8280. reader.onprogress = progressCallBack;
  8281. }
  8282. if (!useArrayBuffer) {
  8283. // Asynchronous read
  8284. reader.readAsText(fileToLoad);
  8285. }
  8286. else {
  8287. reader.readAsArrayBuffer(fileToLoad);
  8288. }
  8289. return request;
  8290. };
  8291. //returns a downloadable url to a file content.
  8292. Tools.FileAsURL = function (content) {
  8293. var fileBlob = new Blob([content]);
  8294. var url = window.URL || window.webkitURL;
  8295. var link = url.createObjectURL(fileBlob);
  8296. return link;
  8297. };
  8298. // Misc.
  8299. Tools.Format = function (value, decimals) {
  8300. if (decimals === void 0) { decimals = 2; }
  8301. return value.toFixed(decimals);
  8302. };
  8303. Tools.CheckExtends = function (v, min, max) {
  8304. if (v.x < min.x)
  8305. min.x = v.x;
  8306. if (v.y < min.y)
  8307. min.y = v.y;
  8308. if (v.z < min.z)
  8309. min.z = v.z;
  8310. if (v.x > max.x)
  8311. max.x = v.x;
  8312. if (v.y > max.y)
  8313. max.y = v.y;
  8314. if (v.z > max.z)
  8315. max.z = v.z;
  8316. };
  8317. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8318. for (var prop in source) {
  8319. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8320. continue;
  8321. }
  8322. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8323. continue;
  8324. }
  8325. var sourceValue = source[prop];
  8326. var typeOfSourceValue = typeof sourceValue;
  8327. if (typeOfSourceValue === "function") {
  8328. continue;
  8329. }
  8330. if (typeOfSourceValue === "object") {
  8331. if (sourceValue instanceof Array) {
  8332. destination[prop] = [];
  8333. if (sourceValue.length > 0) {
  8334. if (typeof sourceValue[0] == "object") {
  8335. for (var index = 0; index < sourceValue.length; index++) {
  8336. var clonedValue = cloneValue(sourceValue[index], destination);
  8337. if (destination[prop].indexOf(clonedValue) === -1) {
  8338. destination[prop].push(clonedValue);
  8339. }
  8340. }
  8341. }
  8342. else {
  8343. destination[prop] = sourceValue.slice(0);
  8344. }
  8345. }
  8346. }
  8347. else {
  8348. destination[prop] = cloneValue(sourceValue, destination);
  8349. }
  8350. }
  8351. else {
  8352. destination[prop] = sourceValue;
  8353. }
  8354. }
  8355. };
  8356. Tools.IsEmpty = function (obj) {
  8357. for (var i in obj) {
  8358. if (obj.hasOwnProperty(i)) {
  8359. return false;
  8360. }
  8361. }
  8362. return true;
  8363. };
  8364. Tools.RegisterTopRootEvents = function (events) {
  8365. for (var index = 0; index < events.length; index++) {
  8366. var event = events[index];
  8367. window.addEventListener(event.name, event.handler, false);
  8368. try {
  8369. if (window.parent) {
  8370. window.parent.addEventListener(event.name, event.handler, false);
  8371. }
  8372. }
  8373. catch (e) {
  8374. // Silently fails...
  8375. }
  8376. }
  8377. };
  8378. Tools.UnregisterTopRootEvents = function (events) {
  8379. for (var index = 0; index < events.length; index++) {
  8380. var event = events[index];
  8381. window.removeEventListener(event.name, event.handler);
  8382. try {
  8383. if (window.parent) {
  8384. window.parent.removeEventListener(event.name, event.handler);
  8385. }
  8386. }
  8387. catch (e) {
  8388. // Silently fails...
  8389. }
  8390. }
  8391. };
  8392. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8393. if (mimeType === void 0) { mimeType = "image/png"; }
  8394. // Read the contents of the framebuffer
  8395. var numberOfChannelsByLine = width * 4;
  8396. var halfHeight = height / 2;
  8397. //Reading datas from WebGL
  8398. var data = engine.readPixels(0, 0, width, height);
  8399. //To flip image on Y axis.
  8400. for (var i = 0; i < halfHeight; i++) {
  8401. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8402. var currentCell = j + i * numberOfChannelsByLine;
  8403. var targetLine = height - i - 1;
  8404. var targetCell = j + targetLine * numberOfChannelsByLine;
  8405. var temp = data[currentCell];
  8406. data[currentCell] = data[targetCell];
  8407. data[targetCell] = temp;
  8408. }
  8409. }
  8410. // Create a 2D canvas to store the result
  8411. if (!screenshotCanvas) {
  8412. screenshotCanvas = document.createElement('canvas');
  8413. }
  8414. screenshotCanvas.width = width;
  8415. screenshotCanvas.height = height;
  8416. var context = screenshotCanvas.getContext('2d');
  8417. if (context) {
  8418. // Copy the pixels to a 2D canvas
  8419. var imageData = context.createImageData(width, height);
  8420. var castData = (imageData.data);
  8421. castData.set(data);
  8422. context.putImageData(imageData, 0, 0);
  8423. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8424. }
  8425. };
  8426. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8427. if (mimeType === void 0) { mimeType = "image/png"; }
  8428. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8429. if (successCallback) {
  8430. successCallback(base64Image);
  8431. }
  8432. else {
  8433. // We need HTMLCanvasElement.toBlob for HD screenshots
  8434. if (!screenshotCanvas.toBlob) {
  8435. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8436. screenshotCanvas.toBlob = function (callback, type, quality) {
  8437. var _this = this;
  8438. setTimeout(function () {
  8439. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8440. for (var i = 0; i < len; i++) {
  8441. arr[i] = binStr.charCodeAt(i);
  8442. }
  8443. callback(new Blob([arr], { type: type || 'image/png' }));
  8444. });
  8445. };
  8446. }
  8447. screenshotCanvas.toBlob(function (blob) {
  8448. var url = URL.createObjectURL(blob);
  8449. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8450. if (("download" in document.createElement("a"))) {
  8451. var a = window.document.createElement("a");
  8452. a.href = url;
  8453. if (fileName) {
  8454. a.setAttribute("download", fileName);
  8455. }
  8456. else {
  8457. var date = new Date();
  8458. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8459. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8460. }
  8461. window.document.body.appendChild(a);
  8462. a.addEventListener("click", function () {
  8463. if (a.parentElement) {
  8464. a.parentElement.removeChild(a);
  8465. }
  8466. });
  8467. a.click();
  8468. }
  8469. else {
  8470. var newWindow = window.open("");
  8471. if (!newWindow)
  8472. return;
  8473. var img = newWindow.document.createElement("img");
  8474. img.onload = function () {
  8475. // no longer need to read the blob so it's revoked
  8476. URL.revokeObjectURL(url);
  8477. };
  8478. img.src = url;
  8479. newWindow.document.body.appendChild(img);
  8480. }
  8481. });
  8482. }
  8483. };
  8484. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8485. if (mimeType === void 0) { mimeType = "image/png"; }
  8486. var width;
  8487. var height;
  8488. // If a precision value is specified
  8489. if (size.precision) {
  8490. width = Math.round(engine.getRenderWidth() * size.precision);
  8491. height = Math.round(width / engine.getAspectRatio(camera));
  8492. }
  8493. else if (size.width && size.height) {
  8494. width = size.width;
  8495. height = size.height;
  8496. }
  8497. else if (size.width && !size.height) {
  8498. width = size.width;
  8499. height = Math.round(width / engine.getAspectRatio(camera));
  8500. }
  8501. else if (size.height && !size.width) {
  8502. height = size.height;
  8503. width = Math.round(height * engine.getAspectRatio(camera));
  8504. }
  8505. else if (!isNaN(size)) {
  8506. height = size;
  8507. width = size;
  8508. }
  8509. else {
  8510. Tools.Error("Invalid 'size' parameter !");
  8511. return;
  8512. }
  8513. if (!screenshotCanvas) {
  8514. screenshotCanvas = document.createElement('canvas');
  8515. }
  8516. screenshotCanvas.width = width;
  8517. screenshotCanvas.height = height;
  8518. var renderContext = screenshotCanvas.getContext("2d");
  8519. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8520. var newWidth = width;
  8521. var newHeight = newWidth / ratio;
  8522. if (newHeight > height) {
  8523. newHeight = height;
  8524. newWidth = newHeight * ratio;
  8525. }
  8526. var offsetX = Math.max(0, width - newWidth) / 2;
  8527. var offsetY = Math.max(0, height - newHeight) / 2;
  8528. var renderingCanvas = engine.getRenderingCanvas();
  8529. if (renderContext && renderingCanvas) {
  8530. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8531. }
  8532. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8533. };
  8534. /**
  8535. * Generates an image screenshot from the specified camera.
  8536. *
  8537. * @param engine The engine to use for rendering
  8538. * @param camera The camera to use for rendering
  8539. * @param size This parameter can be set to a single number or to an object with the
  8540. * following (optional) properties: precision, width, height. If a single number is passed,
  8541. * it will be used for both width and height. If an object is passed, the screenshot size
  8542. * will be derived from the parameters. The precision property is a multiplier allowing
  8543. * rendering at a higher or lower resolution.
  8544. * @param successCallback The callback receives a single parameter which contains the
  8545. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8546. * src parameter of an <img> to display it.
  8547. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8548. * Check your browser for supported MIME types.
  8549. * @param samples Texture samples (default: 1)
  8550. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8551. * @param fileName A name for for the downloaded file.
  8552. * @constructor
  8553. */
  8554. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8555. if (mimeType === void 0) { mimeType = "image/png"; }
  8556. if (samples === void 0) { samples = 1; }
  8557. if (antialiasing === void 0) { antialiasing = false; }
  8558. var width;
  8559. var height;
  8560. //If a precision value is specified
  8561. if (size.precision) {
  8562. width = Math.round(engine.getRenderWidth() * size.precision);
  8563. height = Math.round(width / engine.getAspectRatio(camera));
  8564. size = { width: width, height: height };
  8565. }
  8566. else if (size.width && size.height) {
  8567. width = size.width;
  8568. height = size.height;
  8569. }
  8570. else if (size.width && !size.height) {
  8571. width = size.width;
  8572. height = Math.round(width / engine.getAspectRatio(camera));
  8573. size = { width: width, height: height };
  8574. }
  8575. else if (size.height && !size.width) {
  8576. height = size.height;
  8577. width = Math.round(height * engine.getAspectRatio(camera));
  8578. size = { width: width, height: height };
  8579. }
  8580. else if (!isNaN(size)) {
  8581. height = size;
  8582. width = size;
  8583. }
  8584. else {
  8585. Tools.Error("Invalid 'size' parameter !");
  8586. return;
  8587. }
  8588. var scene = camera.getScene();
  8589. var previousCamera = null;
  8590. if (scene.activeCamera !== camera) {
  8591. previousCamera = scene.activeCamera;
  8592. scene.activeCamera = camera;
  8593. }
  8594. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8595. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8596. texture.renderList = null;
  8597. texture.samples = samples;
  8598. if (antialiasing) {
  8599. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8600. }
  8601. texture.onAfterRenderObservable.add(function () {
  8602. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8603. });
  8604. scene.incrementRenderId();
  8605. scene.resetCachedMaterial();
  8606. texture.render(true);
  8607. texture.dispose();
  8608. if (previousCamera) {
  8609. scene.activeCamera = previousCamera;
  8610. }
  8611. camera.getProjectionMatrix(true); // Force cache refresh;
  8612. };
  8613. // XHR response validator for local file scenario
  8614. Tools.ValidateXHRData = function (xhr, dataType) {
  8615. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8616. if (dataType === void 0) { dataType = 7; }
  8617. try {
  8618. if (dataType & 1) {
  8619. if (xhr.responseText && xhr.responseText.length > 0) {
  8620. return true;
  8621. }
  8622. else if (dataType === 1) {
  8623. return false;
  8624. }
  8625. }
  8626. if (dataType & 2) {
  8627. // Check header width and height since there is no "TGA" magic number
  8628. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8629. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8630. return true;
  8631. }
  8632. else if (dataType === 2) {
  8633. return false;
  8634. }
  8635. }
  8636. if (dataType & 4) {
  8637. // Check for the "DDS" magic number
  8638. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8639. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8640. return true;
  8641. }
  8642. else {
  8643. return false;
  8644. }
  8645. }
  8646. }
  8647. catch (e) {
  8648. // Global protection
  8649. }
  8650. return false;
  8651. };
  8652. /**
  8653. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8654. * Be aware Math.random() could cause collisions, but:
  8655. * "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"
  8656. */
  8657. Tools.RandomId = function () {
  8658. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8659. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8660. return v.toString(16);
  8661. });
  8662. };
  8663. /**
  8664. * Test if the given uri is a base64 string.
  8665. * @param uri The uri to test
  8666. * @return True if the uri is a base64 string or false otherwise.
  8667. */
  8668. Tools.IsBase64 = function (uri) {
  8669. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8670. };
  8671. /**
  8672. * Decode the given base64 uri.
  8673. * @param uri The uri to decode
  8674. * @return The decoded base64 data.
  8675. */
  8676. Tools.DecodeBase64 = function (uri) {
  8677. var decodedString = atob(uri.split(",")[1]);
  8678. var bufferLength = decodedString.length;
  8679. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8680. for (var i = 0; i < bufferLength; i++) {
  8681. bufferView[i] = decodedString.charCodeAt(i);
  8682. }
  8683. return bufferView.buffer;
  8684. };
  8685. Object.defineProperty(Tools, "NoneLogLevel", {
  8686. get: function () {
  8687. return Tools._NoneLogLevel;
  8688. },
  8689. enumerable: true,
  8690. configurable: true
  8691. });
  8692. Object.defineProperty(Tools, "MessageLogLevel", {
  8693. get: function () {
  8694. return Tools._MessageLogLevel;
  8695. },
  8696. enumerable: true,
  8697. configurable: true
  8698. });
  8699. Object.defineProperty(Tools, "WarningLogLevel", {
  8700. get: function () {
  8701. return Tools._WarningLogLevel;
  8702. },
  8703. enumerable: true,
  8704. configurable: true
  8705. });
  8706. Object.defineProperty(Tools, "ErrorLogLevel", {
  8707. get: function () {
  8708. return Tools._ErrorLogLevel;
  8709. },
  8710. enumerable: true,
  8711. configurable: true
  8712. });
  8713. Object.defineProperty(Tools, "AllLogLevel", {
  8714. get: function () {
  8715. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8716. },
  8717. enumerable: true,
  8718. configurable: true
  8719. });
  8720. Tools._AddLogEntry = function (entry) {
  8721. Tools._LogCache = entry + Tools._LogCache;
  8722. if (Tools.OnNewCacheEntry) {
  8723. Tools.OnNewCacheEntry(entry);
  8724. }
  8725. };
  8726. Tools._FormatMessage = function (message) {
  8727. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8728. var date = new Date();
  8729. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8730. };
  8731. Tools._LogDisabled = function (message) {
  8732. // nothing to do
  8733. };
  8734. Tools._LogEnabled = function (message) {
  8735. var formattedMessage = Tools._FormatMessage(message);
  8736. console.log("BJS - " + formattedMessage);
  8737. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8738. Tools._AddLogEntry(entry);
  8739. };
  8740. Tools._WarnDisabled = function (message) {
  8741. // nothing to do
  8742. };
  8743. Tools._WarnEnabled = function (message) {
  8744. var formattedMessage = Tools._FormatMessage(message);
  8745. console.warn("BJS - " + formattedMessage);
  8746. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8747. Tools._AddLogEntry(entry);
  8748. };
  8749. Tools._ErrorDisabled = function (message) {
  8750. // nothing to do
  8751. };
  8752. Tools._ErrorEnabled = function (message) {
  8753. Tools.errorsCount++;
  8754. var formattedMessage = Tools._FormatMessage(message);
  8755. console.error("BJS - " + formattedMessage);
  8756. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8757. Tools._AddLogEntry(entry);
  8758. };
  8759. Object.defineProperty(Tools, "LogCache", {
  8760. get: function () {
  8761. return Tools._LogCache;
  8762. },
  8763. enumerable: true,
  8764. configurable: true
  8765. });
  8766. Tools.ClearLogCache = function () {
  8767. Tools._LogCache = "";
  8768. Tools.errorsCount = 0;
  8769. };
  8770. Object.defineProperty(Tools, "LogLevels", {
  8771. set: function (level) {
  8772. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8773. Tools.Log = Tools._LogEnabled;
  8774. }
  8775. else {
  8776. Tools.Log = Tools._LogDisabled;
  8777. }
  8778. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8779. Tools.Warn = Tools._WarnEnabled;
  8780. }
  8781. else {
  8782. Tools.Warn = Tools._WarnDisabled;
  8783. }
  8784. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8785. Tools.Error = Tools._ErrorEnabled;
  8786. }
  8787. else {
  8788. Tools.Error = Tools._ErrorDisabled;
  8789. }
  8790. },
  8791. enumerable: true,
  8792. configurable: true
  8793. });
  8794. Tools.IsWindowObjectExist = function () {
  8795. return (typeof window) !== "undefined";
  8796. };
  8797. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8798. get: function () {
  8799. return Tools._PerformanceNoneLogLevel;
  8800. },
  8801. enumerable: true,
  8802. configurable: true
  8803. });
  8804. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8805. get: function () {
  8806. return Tools._PerformanceUserMarkLogLevel;
  8807. },
  8808. enumerable: true,
  8809. configurable: true
  8810. });
  8811. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8812. get: function () {
  8813. return Tools._PerformanceConsoleLogLevel;
  8814. },
  8815. enumerable: true,
  8816. configurable: true
  8817. });
  8818. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8819. set: function (level) {
  8820. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8821. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8822. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8823. return;
  8824. }
  8825. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8826. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8827. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8828. return;
  8829. }
  8830. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8831. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8832. },
  8833. enumerable: true,
  8834. configurable: true
  8835. });
  8836. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8837. };
  8838. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8839. };
  8840. Tools._StartUserMark = function (counterName, condition) {
  8841. if (condition === void 0) { condition = true; }
  8842. if (!Tools._performance) {
  8843. if (!Tools.IsWindowObjectExist()) {
  8844. return;
  8845. }
  8846. Tools._performance = window.performance;
  8847. }
  8848. if (!condition || !Tools._performance.mark) {
  8849. return;
  8850. }
  8851. Tools._performance.mark(counterName + "-Begin");
  8852. };
  8853. Tools._EndUserMark = function (counterName, condition) {
  8854. if (condition === void 0) { condition = true; }
  8855. if (!condition || !Tools._performance.mark) {
  8856. return;
  8857. }
  8858. Tools._performance.mark(counterName + "-End");
  8859. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8860. };
  8861. Tools._StartPerformanceConsole = function (counterName, condition) {
  8862. if (condition === void 0) { condition = true; }
  8863. if (!condition) {
  8864. return;
  8865. }
  8866. Tools._StartUserMark(counterName, condition);
  8867. if (console.time) {
  8868. console.time(counterName);
  8869. }
  8870. };
  8871. Tools._EndPerformanceConsole = function (counterName, condition) {
  8872. if (condition === void 0) { condition = true; }
  8873. if (!condition) {
  8874. return;
  8875. }
  8876. Tools._EndUserMark(counterName, condition);
  8877. if (console.time) {
  8878. console.timeEnd(counterName);
  8879. }
  8880. };
  8881. Object.defineProperty(Tools, "Now", {
  8882. get: function () {
  8883. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8884. return window.performance.now();
  8885. }
  8886. return new Date().getTime();
  8887. },
  8888. enumerable: true,
  8889. configurable: true
  8890. });
  8891. /**
  8892. * This method will return the name of the class used to create the instance of the given object.
  8893. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8894. * @param object the object to get the class name from
  8895. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8896. */
  8897. Tools.GetClassName = function (object, isType) {
  8898. if (isType === void 0) { isType = false; }
  8899. var name = null;
  8900. if (!isType && object.getClassName) {
  8901. name = object.getClassName();
  8902. }
  8903. else {
  8904. if (object instanceof Object) {
  8905. var classObj = isType ? object : Object.getPrototypeOf(object);
  8906. name = classObj.constructor["__bjsclassName__"];
  8907. }
  8908. if (!name) {
  8909. name = typeof object;
  8910. }
  8911. }
  8912. return name;
  8913. };
  8914. Tools.First = function (array, predicate) {
  8915. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8916. var el = array_1[_i];
  8917. if (predicate(el)) {
  8918. return el;
  8919. }
  8920. }
  8921. return null;
  8922. };
  8923. /**
  8924. * This method will return the name of the full name of the class, including its owning module (if any).
  8925. * 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).
  8926. * @param object the object to get the class name from
  8927. * @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.
  8928. */
  8929. Tools.getFullClassName = function (object, isType) {
  8930. if (isType === void 0) { isType = false; }
  8931. var className = null;
  8932. var moduleName = null;
  8933. if (!isType && object.getClassName) {
  8934. className = object.getClassName();
  8935. }
  8936. else {
  8937. if (object instanceof Object) {
  8938. var classObj = isType ? object : Object.getPrototypeOf(object);
  8939. className = classObj.constructor["__bjsclassName__"];
  8940. moduleName = classObj.constructor["__bjsmoduleName__"];
  8941. }
  8942. if (!className) {
  8943. className = typeof object;
  8944. }
  8945. }
  8946. if (!className) {
  8947. return null;
  8948. }
  8949. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8950. };
  8951. /**
  8952. * 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.
  8953. * @param array
  8954. */
  8955. Tools.arrayOrStringFeeder = function (array) {
  8956. return function (index) {
  8957. if (index >= array.length) {
  8958. return null;
  8959. }
  8960. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8961. if (val && val.getHashCode) {
  8962. val = val.getHashCode();
  8963. }
  8964. if (typeof val === "string") {
  8965. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8966. }
  8967. return val;
  8968. };
  8969. };
  8970. /**
  8971. * Compute the hashCode of a stream of number
  8972. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8973. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8974. * @return the hash code computed
  8975. */
  8976. Tools.hashCodeFromStream = function (feeder) {
  8977. // Based from here: http://stackoverflow.com/a/7616484/802124
  8978. var hash = 0;
  8979. var index = 0;
  8980. var chr = feeder(index++);
  8981. while (chr != null) {
  8982. hash = ((hash << 5) - hash) + chr;
  8983. hash |= 0; // Convert to 32bit integer
  8984. chr = feeder(index++);
  8985. }
  8986. return hash;
  8987. };
  8988. /**
  8989. * Returns a promise that resolves after the given amount of time.
  8990. * @param delay Number of milliseconds to delay
  8991. * @returns Promise that resolves after the given amount of time
  8992. */
  8993. Tools.DelayAsync = function (delay) {
  8994. return new Promise(function (resolve) {
  8995. setTimeout(function () {
  8996. resolve();
  8997. }, delay);
  8998. });
  8999. };
  9000. Tools.BaseUrl = "";
  9001. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9002. /**
  9003. * Default behaviour for cors in the application.
  9004. * It can be a string if the expected behavior is identical in the entire app.
  9005. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9006. */
  9007. Tools.CorsBehavior = "anonymous";
  9008. Tools.UseFallbackTexture = true;
  9009. /**
  9010. * Use this object to register external classes like custom textures or material
  9011. * to allow the laoders to instantiate them
  9012. */
  9013. Tools.RegisteredExternalClasses = {};
  9014. // Used in case of a texture loading problem
  9015. 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";
  9016. Tools.PreprocessUrl = function (url) {
  9017. return url;
  9018. };
  9019. // Logs
  9020. Tools._NoneLogLevel = 0;
  9021. Tools._MessageLogLevel = 1;
  9022. Tools._WarningLogLevel = 2;
  9023. Tools._ErrorLogLevel = 4;
  9024. Tools._LogCache = "";
  9025. Tools.errorsCount = 0;
  9026. Tools.Log = Tools._LogEnabled;
  9027. Tools.Warn = Tools._WarnEnabled;
  9028. Tools.Error = Tools._ErrorEnabled;
  9029. // Performances
  9030. Tools._PerformanceNoneLogLevel = 0;
  9031. Tools._PerformanceUserMarkLogLevel = 1;
  9032. Tools._PerformanceConsoleLogLevel = 2;
  9033. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9034. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9035. return Tools;
  9036. }());
  9037. BABYLON.Tools = Tools;
  9038. /**
  9039. * This class is used to track a performance counter which is number based.
  9040. * The user has access to many properties which give statistics of different nature
  9041. *
  9042. * The implementer can track two kinds of Performance Counter: time and count
  9043. * 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.
  9044. * 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.
  9045. */
  9046. var PerfCounter = /** @class */ (function () {
  9047. function PerfCounter() {
  9048. this._startMonitoringTime = 0;
  9049. this._min = 0;
  9050. this._max = 0;
  9051. this._average = 0;
  9052. this._lastSecAverage = 0;
  9053. this._current = 0;
  9054. this._totalValueCount = 0;
  9055. this._totalAccumulated = 0;
  9056. this._lastSecAccumulated = 0;
  9057. this._lastSecTime = 0;
  9058. this._lastSecValueCount = 0;
  9059. }
  9060. Object.defineProperty(PerfCounter.prototype, "min", {
  9061. /**
  9062. * Returns the smallest value ever
  9063. */
  9064. get: function () {
  9065. return this._min;
  9066. },
  9067. enumerable: true,
  9068. configurable: true
  9069. });
  9070. Object.defineProperty(PerfCounter.prototype, "max", {
  9071. /**
  9072. * Returns the biggest value ever
  9073. */
  9074. get: function () {
  9075. return this._max;
  9076. },
  9077. enumerable: true,
  9078. configurable: true
  9079. });
  9080. Object.defineProperty(PerfCounter.prototype, "average", {
  9081. /**
  9082. * Returns the average value since the performance counter is running
  9083. */
  9084. get: function () {
  9085. return this._average;
  9086. },
  9087. enumerable: true,
  9088. configurable: true
  9089. });
  9090. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9091. /**
  9092. * Returns the average value of the last second the counter was monitored
  9093. */
  9094. get: function () {
  9095. return this._lastSecAverage;
  9096. },
  9097. enumerable: true,
  9098. configurable: true
  9099. });
  9100. Object.defineProperty(PerfCounter.prototype, "current", {
  9101. /**
  9102. * Returns the current value
  9103. */
  9104. get: function () {
  9105. return this._current;
  9106. },
  9107. enumerable: true,
  9108. configurable: true
  9109. });
  9110. Object.defineProperty(PerfCounter.prototype, "total", {
  9111. get: function () {
  9112. return this._totalAccumulated;
  9113. },
  9114. enumerable: true,
  9115. configurable: true
  9116. });
  9117. Object.defineProperty(PerfCounter.prototype, "count", {
  9118. get: function () {
  9119. return this._totalValueCount;
  9120. },
  9121. enumerable: true,
  9122. configurable: true
  9123. });
  9124. /**
  9125. * Call this method to start monitoring a new frame.
  9126. * 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.
  9127. */
  9128. PerfCounter.prototype.fetchNewFrame = function () {
  9129. this._totalValueCount++;
  9130. this._current = 0;
  9131. this._lastSecValueCount++;
  9132. };
  9133. /**
  9134. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9135. * @param newCount the count value to add to the monitored count
  9136. * @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.
  9137. */
  9138. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9139. if (!PerfCounter.Enabled) {
  9140. return;
  9141. }
  9142. this._current += newCount;
  9143. if (fetchResult) {
  9144. this._fetchResult();
  9145. }
  9146. };
  9147. /**
  9148. * Start monitoring this performance counter
  9149. */
  9150. PerfCounter.prototype.beginMonitoring = function () {
  9151. if (!PerfCounter.Enabled) {
  9152. return;
  9153. }
  9154. this._startMonitoringTime = Tools.Now;
  9155. };
  9156. /**
  9157. * Compute the time lapsed since the previous beginMonitoring() call.
  9158. * @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
  9159. */
  9160. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9161. if (newFrame === void 0) { newFrame = true; }
  9162. if (!PerfCounter.Enabled) {
  9163. return;
  9164. }
  9165. if (newFrame) {
  9166. this.fetchNewFrame();
  9167. }
  9168. var currentTime = Tools.Now;
  9169. this._current = currentTime - this._startMonitoringTime;
  9170. if (newFrame) {
  9171. this._fetchResult();
  9172. }
  9173. };
  9174. PerfCounter.prototype._fetchResult = function () {
  9175. this._totalAccumulated += this._current;
  9176. this._lastSecAccumulated += this._current;
  9177. // Min/Max update
  9178. this._min = Math.min(this._min, this._current);
  9179. this._max = Math.max(this._max, this._current);
  9180. this._average = this._totalAccumulated / this._totalValueCount;
  9181. // Reset last sec?
  9182. var now = Tools.Now;
  9183. if ((now - this._lastSecTime) > 1000) {
  9184. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9185. this._lastSecTime = now;
  9186. this._lastSecAccumulated = 0;
  9187. this._lastSecValueCount = 0;
  9188. }
  9189. };
  9190. PerfCounter.Enabled = true;
  9191. return PerfCounter;
  9192. }());
  9193. BABYLON.PerfCounter = PerfCounter;
  9194. /**
  9195. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9196. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9197. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9198. * @param name The name of the class, case should be preserved
  9199. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9200. */
  9201. function className(name, module) {
  9202. return function (target) {
  9203. target["__bjsclassName__"] = name;
  9204. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9205. };
  9206. }
  9207. BABYLON.className = className;
  9208. /**
  9209. * An implementation of a loop for asynchronous functions.
  9210. */
  9211. var AsyncLoop = /** @class */ (function () {
  9212. /**
  9213. * Constroctor.
  9214. * @param iterations the number of iterations.
  9215. * @param _fn the function to run each iteration
  9216. * @param _successCallback the callback that will be called upon succesful execution
  9217. * @param offset starting offset.
  9218. */
  9219. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9220. if (offset === void 0) { offset = 0; }
  9221. this.iterations = iterations;
  9222. this._fn = _fn;
  9223. this._successCallback = _successCallback;
  9224. this.index = offset - 1;
  9225. this._done = false;
  9226. }
  9227. /**
  9228. * Execute the next iteration. Must be called after the last iteration was finished.
  9229. */
  9230. AsyncLoop.prototype.executeNext = function () {
  9231. if (!this._done) {
  9232. if (this.index + 1 < this.iterations) {
  9233. ++this.index;
  9234. this._fn(this);
  9235. }
  9236. else {
  9237. this.breakLoop();
  9238. }
  9239. }
  9240. };
  9241. /**
  9242. * Break the loop and run the success callback.
  9243. */
  9244. AsyncLoop.prototype.breakLoop = function () {
  9245. this._done = true;
  9246. this._successCallback();
  9247. };
  9248. /**
  9249. * Helper function
  9250. */
  9251. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9252. if (offset === void 0) { offset = 0; }
  9253. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9254. loop.executeNext();
  9255. return loop;
  9256. };
  9257. /**
  9258. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9259. * @param iterations total number of iterations
  9260. * @param syncedIterations number of synchronous iterations in each async iteration.
  9261. * @param fn the function to call each iteration.
  9262. * @param callback a success call back that will be called when iterating stops.
  9263. * @param breakFunction a break condition (optional)
  9264. * @param timeout timeout settings for the setTimeout function. default - 0.
  9265. * @constructor
  9266. */
  9267. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9268. if (timeout === void 0) { timeout = 0; }
  9269. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9270. if (breakFunction && breakFunction())
  9271. loop.breakLoop();
  9272. else {
  9273. setTimeout(function () {
  9274. for (var i = 0; i < syncedIterations; ++i) {
  9275. var iteration = (loop.index * syncedIterations) + i;
  9276. if (iteration >= iterations)
  9277. break;
  9278. fn(iteration);
  9279. if (breakFunction && breakFunction()) {
  9280. loop.breakLoop();
  9281. break;
  9282. }
  9283. }
  9284. loop.executeNext();
  9285. }, timeout);
  9286. }
  9287. }, callback);
  9288. };
  9289. return AsyncLoop;
  9290. }());
  9291. BABYLON.AsyncLoop = AsyncLoop;
  9292. })(BABYLON || (BABYLON = {}));
  9293. //# sourceMappingURL=babylon.tools.js.map
  9294. var BABYLON;
  9295. (function (BABYLON) {
  9296. var PromiseStates;
  9297. (function (PromiseStates) {
  9298. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9299. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9300. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9301. })(PromiseStates || (PromiseStates = {}));
  9302. var FulFillmentAgregator = /** @class */ (function () {
  9303. function FulFillmentAgregator() {
  9304. this.count = 0;
  9305. this.target = 0;
  9306. this.results = [];
  9307. }
  9308. return FulFillmentAgregator;
  9309. }());
  9310. var InternalPromise = /** @class */ (function () {
  9311. function InternalPromise(resolver) {
  9312. var _this = this;
  9313. this._state = PromiseStates.Pending;
  9314. this._children = new Array();
  9315. this._rejectWasConsumed = false;
  9316. if (!resolver) {
  9317. return;
  9318. }
  9319. try {
  9320. resolver(function (value) {
  9321. _this._resolve(value);
  9322. }, function (reason) {
  9323. _this._reject(reason);
  9324. });
  9325. }
  9326. catch (e) {
  9327. this._reject(e);
  9328. }
  9329. }
  9330. InternalPromise.prototype.catch = function (onRejected) {
  9331. return this.then(undefined, onRejected);
  9332. };
  9333. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9334. var _this = this;
  9335. var newPromise = new InternalPromise();
  9336. newPromise._onFulfilled = onFulfilled;
  9337. newPromise._onRejected = onRejected;
  9338. // Composition
  9339. this._children.push(newPromise);
  9340. if (this._state !== PromiseStates.Pending) {
  9341. BABYLON.Tools.SetImmediate(function () {
  9342. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9343. var returnedValue = newPromise._resolve(_this._result);
  9344. if (returnedValue !== undefined && returnedValue !== null) {
  9345. if (returnedValue._state !== undefined) {
  9346. var returnedPromise = returnedValue;
  9347. newPromise._children.push(returnedPromise);
  9348. newPromise = returnedPromise;
  9349. }
  9350. else {
  9351. newPromise._result = returnedValue;
  9352. }
  9353. }
  9354. }
  9355. else {
  9356. newPromise._reject(_this._reason);
  9357. }
  9358. });
  9359. }
  9360. return newPromise;
  9361. };
  9362. InternalPromise.prototype._moveChildren = function (children) {
  9363. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9364. if (this._state === PromiseStates.Fulfilled) {
  9365. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9366. var child = _b[_i];
  9367. child._resolve(this._result);
  9368. }
  9369. }
  9370. else if (this._state === PromiseStates.Rejected) {
  9371. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9372. var child = _d[_c];
  9373. child._reject(this._reason);
  9374. }
  9375. }
  9376. var _a;
  9377. };
  9378. InternalPromise.prototype._resolve = function (value) {
  9379. try {
  9380. this._state = PromiseStates.Fulfilled;
  9381. this._result = value;
  9382. var returnedValue = null;
  9383. if (this._onFulfilled) {
  9384. returnedValue = this._onFulfilled(value);
  9385. }
  9386. if (returnedValue !== undefined && returnedValue !== null) {
  9387. if (returnedValue._state !== undefined) {
  9388. // Transmit children
  9389. var returnedPromise = returnedValue;
  9390. returnedPromise._moveChildren(this._children);
  9391. }
  9392. else {
  9393. value = returnedValue;
  9394. }
  9395. }
  9396. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9397. var child = _a[_i];
  9398. child._resolve(value);
  9399. }
  9400. this._children.length = 0;
  9401. delete this._onFulfilled;
  9402. delete this._onRejected;
  9403. return returnedValue;
  9404. }
  9405. catch (e) {
  9406. this._reject(e, true);
  9407. }
  9408. return null;
  9409. };
  9410. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9411. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9412. this._state = PromiseStates.Rejected;
  9413. this._reason = reason;
  9414. if (this._onRejected && !onLocalThrow) {
  9415. try {
  9416. this._onRejected(reason);
  9417. this._rejectWasConsumed = true;
  9418. }
  9419. catch (e) {
  9420. reason = e;
  9421. }
  9422. }
  9423. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9424. var child = _a[_i];
  9425. if (this._rejectWasConsumed) {
  9426. child._resolve(null);
  9427. }
  9428. else {
  9429. child._reject(reason);
  9430. }
  9431. }
  9432. this._children.length = 0;
  9433. delete this._onFulfilled;
  9434. delete this._onRejected;
  9435. };
  9436. InternalPromise.resolve = function (value) {
  9437. var newPromise = new InternalPromise();
  9438. newPromise._resolve(value);
  9439. return newPromise;
  9440. };
  9441. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9442. promise.then(function (value) {
  9443. agregator.results[index] = value;
  9444. agregator.count++;
  9445. if (agregator.count === agregator.target) {
  9446. agregator.rootPromise._resolve(agregator.results);
  9447. }
  9448. return null;
  9449. }, function (reason) {
  9450. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9451. agregator.rootPromise._reject(reason);
  9452. }
  9453. });
  9454. };
  9455. InternalPromise.all = function (promises) {
  9456. var newPromise = new InternalPromise();
  9457. var agregator = new FulFillmentAgregator();
  9458. agregator.target = promises.length;
  9459. agregator.rootPromise = newPromise;
  9460. if (promises.length) {
  9461. for (var index = 0; index < promises.length; index++) {
  9462. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9463. }
  9464. }
  9465. else {
  9466. newPromise._resolve([]);
  9467. }
  9468. return newPromise;
  9469. };
  9470. return InternalPromise;
  9471. }());
  9472. /**
  9473. * Helper class that provides a small promise polyfill
  9474. */
  9475. var PromisePolyfill = /** @class */ (function () {
  9476. function PromisePolyfill() {
  9477. }
  9478. /**
  9479. * Static function used to check if the polyfill is required
  9480. * If this is the case then the function will inject the polyfill to window.Promise
  9481. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9482. */
  9483. PromisePolyfill.Apply = function (force) {
  9484. if (force === void 0) { force = false; }
  9485. if (force || typeof Promise === 'undefined') {
  9486. var root = window;
  9487. root.Promise = InternalPromise;
  9488. }
  9489. };
  9490. return PromisePolyfill;
  9491. }());
  9492. BABYLON.PromisePolyfill = PromisePolyfill;
  9493. })(BABYLON || (BABYLON = {}));
  9494. //# sourceMappingURL=babylon.promise.js.map
  9495. var BABYLON;
  9496. (function (BABYLON) {
  9497. var _AlphaState = /** @class */ (function () {
  9498. /**
  9499. * Initializes the state.
  9500. */
  9501. function _AlphaState() {
  9502. this._isAlphaBlendDirty = false;
  9503. this._isBlendFunctionParametersDirty = false;
  9504. this._isBlendEquationParametersDirty = false;
  9505. this._isBlendConstantsDirty = false;
  9506. this._alphaBlend = false;
  9507. this._blendFunctionParameters = new Array(4);
  9508. this._blendEquationParameters = new Array(2);
  9509. this._blendConstants = new Array(4);
  9510. this.reset();
  9511. }
  9512. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9513. get: function () {
  9514. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9515. },
  9516. enumerable: true,
  9517. configurable: true
  9518. });
  9519. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9520. get: function () {
  9521. return this._alphaBlend;
  9522. },
  9523. set: function (value) {
  9524. if (this._alphaBlend === value) {
  9525. return;
  9526. }
  9527. this._alphaBlend = value;
  9528. this._isAlphaBlendDirty = true;
  9529. },
  9530. enumerable: true,
  9531. configurable: true
  9532. });
  9533. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9534. if (this._blendConstants[0] === r &&
  9535. this._blendConstants[1] === g &&
  9536. this._blendConstants[2] === b &&
  9537. this._blendConstants[3] === a) {
  9538. return;
  9539. }
  9540. this._blendConstants[0] = r;
  9541. this._blendConstants[1] = g;
  9542. this._blendConstants[2] = b;
  9543. this._blendConstants[3] = a;
  9544. this._isBlendConstantsDirty = true;
  9545. };
  9546. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9547. if (this._blendFunctionParameters[0] === value0 &&
  9548. this._blendFunctionParameters[1] === value1 &&
  9549. this._blendFunctionParameters[2] === value2 &&
  9550. this._blendFunctionParameters[3] === value3) {
  9551. return;
  9552. }
  9553. this._blendFunctionParameters[0] = value0;
  9554. this._blendFunctionParameters[1] = value1;
  9555. this._blendFunctionParameters[2] = value2;
  9556. this._blendFunctionParameters[3] = value3;
  9557. this._isBlendFunctionParametersDirty = true;
  9558. };
  9559. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9560. if (this._blendEquationParameters[0] === rgb &&
  9561. this._blendEquationParameters[1] === alpha) {
  9562. return;
  9563. }
  9564. this._blendEquationParameters[0] = rgb;
  9565. this._blendEquationParameters[1] = alpha;
  9566. this._isBlendEquationParametersDirty = true;
  9567. };
  9568. _AlphaState.prototype.reset = function () {
  9569. this._alphaBlend = false;
  9570. this._blendFunctionParameters[0] = null;
  9571. this._blendFunctionParameters[1] = null;
  9572. this._blendFunctionParameters[2] = null;
  9573. this._blendFunctionParameters[3] = null;
  9574. this._blendEquationParameters[0] = null;
  9575. this._blendEquationParameters[1] = null;
  9576. this._blendConstants[0] = null;
  9577. this._blendConstants[1] = null;
  9578. this._blendConstants[2] = null;
  9579. this._blendConstants[3] = null;
  9580. this._isAlphaBlendDirty = true;
  9581. this._isBlendFunctionParametersDirty = false;
  9582. this._isBlendEquationParametersDirty = false;
  9583. this._isBlendConstantsDirty = false;
  9584. };
  9585. _AlphaState.prototype.apply = function (gl) {
  9586. if (!this.isDirty) {
  9587. return;
  9588. }
  9589. // Alpha blend
  9590. if (this._isAlphaBlendDirty) {
  9591. if (this._alphaBlend) {
  9592. gl.enable(gl.BLEND);
  9593. }
  9594. else {
  9595. gl.disable(gl.BLEND);
  9596. }
  9597. this._isAlphaBlendDirty = false;
  9598. }
  9599. // Alpha function
  9600. if (this._isBlendFunctionParametersDirty) {
  9601. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9602. this._isBlendFunctionParametersDirty = false;
  9603. }
  9604. // Alpha equation
  9605. if (this._isBlendEquationParametersDirty) {
  9606. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9607. this._isBlendEquationParametersDirty = false;
  9608. }
  9609. // Constants
  9610. if (this._isBlendConstantsDirty) {
  9611. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9612. this._isBlendConstantsDirty = false;
  9613. }
  9614. };
  9615. return _AlphaState;
  9616. }());
  9617. BABYLON._AlphaState = _AlphaState;
  9618. })(BABYLON || (BABYLON = {}));
  9619. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9620. var BABYLON;
  9621. (function (BABYLON) {
  9622. var _DepthCullingState = /** @class */ (function () {
  9623. /**
  9624. * Initializes the state.
  9625. */
  9626. function _DepthCullingState() {
  9627. this._isDepthTestDirty = false;
  9628. this._isDepthMaskDirty = false;
  9629. this._isDepthFuncDirty = false;
  9630. this._isCullFaceDirty = false;
  9631. this._isCullDirty = false;
  9632. this._isZOffsetDirty = false;
  9633. this._isFrontFaceDirty = false;
  9634. this.reset();
  9635. }
  9636. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9637. get: function () {
  9638. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9639. },
  9640. enumerable: true,
  9641. configurable: true
  9642. });
  9643. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9644. get: function () {
  9645. return this._zOffset;
  9646. },
  9647. set: function (value) {
  9648. if (this._zOffset === value) {
  9649. return;
  9650. }
  9651. this._zOffset = value;
  9652. this._isZOffsetDirty = true;
  9653. },
  9654. enumerable: true,
  9655. configurable: true
  9656. });
  9657. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9658. get: function () {
  9659. return this._cullFace;
  9660. },
  9661. set: function (value) {
  9662. if (this._cullFace === value) {
  9663. return;
  9664. }
  9665. this._cullFace = value;
  9666. this._isCullFaceDirty = true;
  9667. },
  9668. enumerable: true,
  9669. configurable: true
  9670. });
  9671. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9672. get: function () {
  9673. return this._cull;
  9674. },
  9675. set: function (value) {
  9676. if (this._cull === value) {
  9677. return;
  9678. }
  9679. this._cull = value;
  9680. this._isCullDirty = true;
  9681. },
  9682. enumerable: true,
  9683. configurable: true
  9684. });
  9685. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9686. get: function () {
  9687. return this._depthFunc;
  9688. },
  9689. set: function (value) {
  9690. if (this._depthFunc === value) {
  9691. return;
  9692. }
  9693. this._depthFunc = value;
  9694. this._isDepthFuncDirty = true;
  9695. },
  9696. enumerable: true,
  9697. configurable: true
  9698. });
  9699. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9700. get: function () {
  9701. return this._depthMask;
  9702. },
  9703. set: function (value) {
  9704. if (this._depthMask === value) {
  9705. return;
  9706. }
  9707. this._depthMask = value;
  9708. this._isDepthMaskDirty = true;
  9709. },
  9710. enumerable: true,
  9711. configurable: true
  9712. });
  9713. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9714. get: function () {
  9715. return this._depthTest;
  9716. },
  9717. set: function (value) {
  9718. if (this._depthTest === value) {
  9719. return;
  9720. }
  9721. this._depthTest = value;
  9722. this._isDepthTestDirty = true;
  9723. },
  9724. enumerable: true,
  9725. configurable: true
  9726. });
  9727. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9728. get: function () {
  9729. return this._frontFace;
  9730. },
  9731. set: function (value) {
  9732. if (this._frontFace === value) {
  9733. return;
  9734. }
  9735. this._frontFace = value;
  9736. this._isFrontFaceDirty = true;
  9737. },
  9738. enumerable: true,
  9739. configurable: true
  9740. });
  9741. _DepthCullingState.prototype.reset = function () {
  9742. this._depthMask = true;
  9743. this._depthTest = true;
  9744. this._depthFunc = null;
  9745. this._cullFace = null;
  9746. this._cull = null;
  9747. this._zOffset = 0;
  9748. this._frontFace = null;
  9749. this._isDepthTestDirty = true;
  9750. this._isDepthMaskDirty = true;
  9751. this._isDepthFuncDirty = false;
  9752. this._isCullFaceDirty = false;
  9753. this._isCullDirty = false;
  9754. this._isZOffsetDirty = false;
  9755. this._isFrontFaceDirty = false;
  9756. };
  9757. _DepthCullingState.prototype.apply = function (gl) {
  9758. if (!this.isDirty) {
  9759. return;
  9760. }
  9761. // Cull
  9762. if (this._isCullDirty) {
  9763. if (this.cull) {
  9764. gl.enable(gl.CULL_FACE);
  9765. }
  9766. else {
  9767. gl.disable(gl.CULL_FACE);
  9768. }
  9769. this._isCullDirty = false;
  9770. }
  9771. // Cull face
  9772. if (this._isCullFaceDirty) {
  9773. gl.cullFace(this.cullFace);
  9774. this._isCullFaceDirty = false;
  9775. }
  9776. // Depth mask
  9777. if (this._isDepthMaskDirty) {
  9778. gl.depthMask(this.depthMask);
  9779. this._isDepthMaskDirty = false;
  9780. }
  9781. // Depth test
  9782. if (this._isDepthTestDirty) {
  9783. if (this.depthTest) {
  9784. gl.enable(gl.DEPTH_TEST);
  9785. }
  9786. else {
  9787. gl.disable(gl.DEPTH_TEST);
  9788. }
  9789. this._isDepthTestDirty = false;
  9790. }
  9791. // Depth func
  9792. if (this._isDepthFuncDirty) {
  9793. gl.depthFunc(this.depthFunc);
  9794. this._isDepthFuncDirty = false;
  9795. }
  9796. // zOffset
  9797. if (this._isZOffsetDirty) {
  9798. if (this.zOffset) {
  9799. gl.enable(gl.POLYGON_OFFSET_FILL);
  9800. gl.polygonOffset(this.zOffset, 0);
  9801. }
  9802. else {
  9803. gl.disable(gl.POLYGON_OFFSET_FILL);
  9804. }
  9805. this._isZOffsetDirty = false;
  9806. }
  9807. // Front face
  9808. if (this._isFrontFaceDirty) {
  9809. gl.frontFace(this.frontFace);
  9810. this._isFrontFaceDirty = false;
  9811. }
  9812. };
  9813. return _DepthCullingState;
  9814. }());
  9815. BABYLON._DepthCullingState = _DepthCullingState;
  9816. })(BABYLON || (BABYLON = {}));
  9817. //# sourceMappingURL=babylon.depthCullingState.js.map
  9818. var BABYLON;
  9819. (function (BABYLON) {
  9820. var _StencilState = /** @class */ (function () {
  9821. function _StencilState() {
  9822. this._isStencilTestDirty = false;
  9823. this._isStencilMaskDirty = false;
  9824. this._isStencilFuncDirty = false;
  9825. this._isStencilOpDirty = false;
  9826. this.reset();
  9827. }
  9828. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9829. get: function () {
  9830. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9831. },
  9832. enumerable: true,
  9833. configurable: true
  9834. });
  9835. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9836. get: function () {
  9837. return this._stencilFunc;
  9838. },
  9839. set: function (value) {
  9840. if (this._stencilFunc === value) {
  9841. return;
  9842. }
  9843. this._stencilFunc = value;
  9844. this._isStencilFuncDirty = true;
  9845. },
  9846. enumerable: true,
  9847. configurable: true
  9848. });
  9849. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9850. get: function () {
  9851. return this._stencilFuncRef;
  9852. },
  9853. set: function (value) {
  9854. if (this._stencilFuncRef === value) {
  9855. return;
  9856. }
  9857. this._stencilFuncRef = value;
  9858. this._isStencilFuncDirty = true;
  9859. },
  9860. enumerable: true,
  9861. configurable: true
  9862. });
  9863. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9864. get: function () {
  9865. return this._stencilFuncMask;
  9866. },
  9867. set: function (value) {
  9868. if (this._stencilFuncMask === value) {
  9869. return;
  9870. }
  9871. this._stencilFuncMask = value;
  9872. this._isStencilFuncDirty = true;
  9873. },
  9874. enumerable: true,
  9875. configurable: true
  9876. });
  9877. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9878. get: function () {
  9879. return this._stencilOpStencilFail;
  9880. },
  9881. set: function (value) {
  9882. if (this._stencilOpStencilFail === value) {
  9883. return;
  9884. }
  9885. this._stencilOpStencilFail = value;
  9886. this._isStencilOpDirty = true;
  9887. },
  9888. enumerable: true,
  9889. configurable: true
  9890. });
  9891. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9892. get: function () {
  9893. return this._stencilOpDepthFail;
  9894. },
  9895. set: function (value) {
  9896. if (this._stencilOpDepthFail === value) {
  9897. return;
  9898. }
  9899. this._stencilOpDepthFail = value;
  9900. this._isStencilOpDirty = true;
  9901. },
  9902. enumerable: true,
  9903. configurable: true
  9904. });
  9905. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9906. get: function () {
  9907. return this._stencilOpStencilDepthPass;
  9908. },
  9909. set: function (value) {
  9910. if (this._stencilOpStencilDepthPass === value) {
  9911. return;
  9912. }
  9913. this._stencilOpStencilDepthPass = value;
  9914. this._isStencilOpDirty = true;
  9915. },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9920. get: function () {
  9921. return this._stencilMask;
  9922. },
  9923. set: function (value) {
  9924. if (this._stencilMask === value) {
  9925. return;
  9926. }
  9927. this._stencilMask = value;
  9928. this._isStencilMaskDirty = true;
  9929. },
  9930. enumerable: true,
  9931. configurable: true
  9932. });
  9933. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9934. get: function () {
  9935. return this._stencilTest;
  9936. },
  9937. set: function (value) {
  9938. if (this._stencilTest === value) {
  9939. return;
  9940. }
  9941. this._stencilTest = value;
  9942. this._isStencilTestDirty = true;
  9943. },
  9944. enumerable: true,
  9945. configurable: true
  9946. });
  9947. _StencilState.prototype.reset = function () {
  9948. this._stencilTest = false;
  9949. this._stencilMask = 0xFF;
  9950. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9951. this._stencilFuncRef = 1;
  9952. this._stencilFuncMask = 0xFF;
  9953. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9954. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9955. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9956. this._isStencilTestDirty = true;
  9957. this._isStencilMaskDirty = true;
  9958. this._isStencilFuncDirty = true;
  9959. this._isStencilOpDirty = true;
  9960. };
  9961. _StencilState.prototype.apply = function (gl) {
  9962. if (!this.isDirty) {
  9963. return;
  9964. }
  9965. // Stencil test
  9966. if (this._isStencilTestDirty) {
  9967. if (this.stencilTest) {
  9968. gl.enable(gl.STENCIL_TEST);
  9969. }
  9970. else {
  9971. gl.disable(gl.STENCIL_TEST);
  9972. }
  9973. this._isStencilTestDirty = false;
  9974. }
  9975. // Stencil mask
  9976. if (this._isStencilMaskDirty) {
  9977. gl.stencilMask(this.stencilMask);
  9978. this._isStencilMaskDirty = false;
  9979. }
  9980. // Stencil func
  9981. if (this._isStencilFuncDirty) {
  9982. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9983. this._isStencilFuncDirty = false;
  9984. }
  9985. // Stencil op
  9986. if (this._isStencilOpDirty) {
  9987. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9988. this._isStencilOpDirty = false;
  9989. }
  9990. };
  9991. return _StencilState;
  9992. }());
  9993. BABYLON._StencilState = _StencilState;
  9994. })(BABYLON || (BABYLON = {}));
  9995. //# sourceMappingURL=babylon.stencilState.js.map
  9996. var __assign = (this && this.__assign) || Object.assign || function(t) {
  9997. for (var s, i = 1, n = arguments.length; i < n; i++) {
  9998. s = arguments[i];
  9999. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10000. t[p] = s[p];
  10001. }
  10002. return t;
  10003. };
  10004. var BABYLON;
  10005. (function (BABYLON) {
  10006. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10007. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10008. };
  10009. var compileRawShader = function (gl, source, type) {
  10010. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10011. gl.shaderSource(shader, source);
  10012. gl.compileShader(shader);
  10013. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10014. var log = gl.getShaderInfoLog(shader);
  10015. if (log) {
  10016. throw new Error(log);
  10017. }
  10018. }
  10019. if (!shader) {
  10020. throw new Error("Something went wrong while compile the shader.");
  10021. }
  10022. return shader;
  10023. };
  10024. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10025. var magFilter = gl.NEAREST;
  10026. var minFilter = gl.NEAREST;
  10027. switch (samplingMode) {
  10028. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10029. magFilter = gl.LINEAR;
  10030. if (generateMipMaps) {
  10031. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10032. }
  10033. else {
  10034. minFilter = gl.LINEAR;
  10035. }
  10036. break;
  10037. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10038. magFilter = gl.LINEAR;
  10039. if (generateMipMaps) {
  10040. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10041. }
  10042. else {
  10043. minFilter = gl.LINEAR;
  10044. }
  10045. break;
  10046. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10047. magFilter = gl.NEAREST;
  10048. if (generateMipMaps) {
  10049. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10050. }
  10051. else {
  10052. minFilter = gl.NEAREST;
  10053. }
  10054. break;
  10055. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10056. magFilter = gl.NEAREST;
  10057. if (generateMipMaps) {
  10058. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10059. }
  10060. else {
  10061. minFilter = gl.NEAREST;
  10062. }
  10063. break;
  10064. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10065. magFilter = gl.NEAREST;
  10066. if (generateMipMaps) {
  10067. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10068. }
  10069. else {
  10070. minFilter = gl.LINEAR;
  10071. }
  10072. break;
  10073. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10074. magFilter = gl.NEAREST;
  10075. if (generateMipMaps) {
  10076. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10077. }
  10078. else {
  10079. minFilter = gl.LINEAR;
  10080. }
  10081. break;
  10082. case BABYLON.Texture.NEAREST_LINEAR:
  10083. magFilter = gl.NEAREST;
  10084. minFilter = gl.LINEAR;
  10085. break;
  10086. case BABYLON.Texture.NEAREST_NEAREST:
  10087. magFilter = gl.NEAREST;
  10088. minFilter = gl.NEAREST;
  10089. break;
  10090. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10091. magFilter = gl.LINEAR;
  10092. if (generateMipMaps) {
  10093. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10094. }
  10095. else {
  10096. minFilter = gl.NEAREST;
  10097. }
  10098. break;
  10099. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10100. magFilter = gl.LINEAR;
  10101. if (generateMipMaps) {
  10102. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10103. }
  10104. else {
  10105. minFilter = gl.NEAREST;
  10106. }
  10107. break;
  10108. case BABYLON.Texture.LINEAR_LINEAR:
  10109. magFilter = gl.LINEAR;
  10110. minFilter = gl.LINEAR;
  10111. break;
  10112. case BABYLON.Texture.LINEAR_NEAREST:
  10113. magFilter = gl.LINEAR;
  10114. minFilter = gl.NEAREST;
  10115. break;
  10116. }
  10117. return {
  10118. min: minFilter,
  10119. mag: magFilter
  10120. };
  10121. };
  10122. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10123. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10124. var img;
  10125. var onload = function () {
  10126. loadedImages[index] = img;
  10127. loadedImages._internalCount++;
  10128. if (scene) {
  10129. scene._removePendingData(img);
  10130. }
  10131. if (loadedImages._internalCount === 6) {
  10132. onfinish(loadedImages);
  10133. }
  10134. };
  10135. var onerror = function (message, exception) {
  10136. if (scene) {
  10137. scene._removePendingData(img);
  10138. }
  10139. if (onErrorCallBack) {
  10140. onErrorCallBack(message, exception);
  10141. }
  10142. };
  10143. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10144. if (scene) {
  10145. scene._addPendingData(img);
  10146. }
  10147. };
  10148. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10149. if (onError === void 0) { onError = null; }
  10150. var loadedImages = [];
  10151. loadedImages._internalCount = 0;
  10152. for (var index = 0; index < 6; index++) {
  10153. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10154. }
  10155. };
  10156. var BufferPointer = /** @class */ (function () {
  10157. function BufferPointer() {
  10158. }
  10159. return BufferPointer;
  10160. }());
  10161. var InstancingAttributeInfo = /** @class */ (function () {
  10162. function InstancingAttributeInfo() {
  10163. }
  10164. return InstancingAttributeInfo;
  10165. }());
  10166. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10167. /**
  10168. * Define options used to create a render target texture
  10169. */
  10170. var RenderTargetCreationOptions = /** @class */ (function () {
  10171. function RenderTargetCreationOptions() {
  10172. }
  10173. return RenderTargetCreationOptions;
  10174. }());
  10175. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10176. /**
  10177. * Regroup several parameters relative to the browser in use
  10178. */
  10179. var EngineCapabilities = /** @class */ (function () {
  10180. function EngineCapabilities() {
  10181. }
  10182. return EngineCapabilities;
  10183. }());
  10184. BABYLON.EngineCapabilities = EngineCapabilities;
  10185. /**
  10186. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10187. */
  10188. var Engine = /** @class */ (function () {
  10189. /**
  10190. * @constructor
  10191. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10192. * @param antialias defines enable antialiasing (default: false)
  10193. * @param options defines further options to be sent to the getContext() function
  10194. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10195. */
  10196. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10197. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10198. var _this = this;
  10199. // Public members
  10200. this.forcePOTTextures = false;
  10201. this.isFullscreen = false;
  10202. this.isPointerLock = false;
  10203. this.cullBackFaces = true;
  10204. this.renderEvenInBackground = true;
  10205. this.preventCacheWipeBetweenFrames = false;
  10206. // To enable/disable IDB support and avoid XHR on .manifest
  10207. this.enableOfflineSupport = false;
  10208. this.scenes = new Array();
  10209. this.postProcesses = new Array();
  10210. // Observables
  10211. /**
  10212. * Observable event triggered each time the rendering canvas is resized
  10213. */
  10214. this.onResizeObservable = new BABYLON.Observable();
  10215. /**
  10216. * Observable event triggered each time the canvas loses focus
  10217. */
  10218. this.onCanvasBlurObservable = new BABYLON.Observable();
  10219. /**
  10220. * Observable event triggered each time the canvas gains focus
  10221. */
  10222. this.onCanvasFocusObservable = new BABYLON.Observable();
  10223. /**
  10224. * Observable event triggered each time the canvas receives pointerout event
  10225. */
  10226. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10227. /**
  10228. * Observable event triggered before each texture is initialized
  10229. */
  10230. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10231. //WebVR
  10232. this._vrDisplay = undefined;
  10233. this._vrSupported = false;
  10234. this._vrExclusivePointerMode = false;
  10235. // Uniform buffers list
  10236. this.disableUniformBuffers = false;
  10237. this._uniformBuffers = new Array();
  10238. // Observables
  10239. /**
  10240. * Observable raised when the engine begins a new frame
  10241. */
  10242. this.onBeginFrameObservable = new BABYLON.Observable();
  10243. /**
  10244. * Observable raised when the engine ends the current frame
  10245. */
  10246. this.onEndFrameObservable = new BABYLON.Observable();
  10247. /**
  10248. * Observable raised when the engine is about to compile a shader
  10249. */
  10250. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10251. /**
  10252. * Observable raised when the engine has jsut compiled a shader
  10253. */
  10254. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10255. this._windowIsBackground = false;
  10256. this._webGLVersion = 1.0;
  10257. this._badOS = false;
  10258. this._badDesktopOS = false;
  10259. /**
  10260. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10261. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10262. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10263. */
  10264. this.disableTextureBindingOptimization = false;
  10265. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10266. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10267. this.onVRRequestPresentStart = new BABYLON.Observable();
  10268. this._colorWrite = true;
  10269. this._drawCalls = new BABYLON.PerfCounter();
  10270. this._textureCollisions = new BABYLON.PerfCounter();
  10271. this._renderingQueueLaunched = false;
  10272. this._activeRenderLoops = new Array();
  10273. // Deterministic lockstepMaxSteps
  10274. this._deterministicLockstep = false;
  10275. this._lockstepMaxSteps = 4;
  10276. // Lost context
  10277. this.onContextLostObservable = new BABYLON.Observable();
  10278. this.onContextRestoredObservable = new BABYLON.Observable();
  10279. this._contextWasLost = false;
  10280. this._doNotHandleContextLost = false;
  10281. // FPS
  10282. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10283. this._fps = 60;
  10284. this._deltaTime = 0;
  10285. /**
  10286. * Turn this value on if you want to pause FPS computation when in background
  10287. */
  10288. this.disablePerformanceMonitorInBackground = false;
  10289. // States
  10290. this._depthCullingState = new BABYLON._DepthCullingState();
  10291. this._stencilState = new BABYLON._StencilState();
  10292. this._alphaState = new BABYLON._AlphaState();
  10293. this._alphaMode = Engine.ALPHA_DISABLE;
  10294. // Cache
  10295. this._internalTexturesCache = new Array();
  10296. this._activeChannel = 0;
  10297. this._currentTextureChannel = -1;
  10298. this._boundTexturesCache = {};
  10299. this._compiledEffects = {};
  10300. this._vertexAttribArraysEnabled = [];
  10301. this._uintIndicesCurrentlySet = false;
  10302. this._currentBoundBuffer = new Array();
  10303. this._currentBufferPointers = new Array();
  10304. this._currentInstanceLocations = new Array();
  10305. this._currentInstanceBuffers = new Array();
  10306. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10307. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10308. this._vaoRecordInProgress = false;
  10309. this._mustWipeVertexAttributes = false;
  10310. this._nextFreeTextureSlots = new Array();
  10311. this._maxSimultaneousTextures = 0;
  10312. this._activeRequests = new Array();
  10313. // Hardware supported Compressed Textures
  10314. this._texturesSupported = new Array();
  10315. this._onVRFullScreenTriggered = function () {
  10316. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10317. //get the old size before we change
  10318. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10319. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10320. //get the width and height, change the render size
  10321. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10322. _this.setHardwareScalingLevel(1);
  10323. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10324. }
  10325. else {
  10326. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10327. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10328. }
  10329. };
  10330. this._boundUniforms = {};
  10331. // Register promises
  10332. BABYLON.PromisePolyfill.Apply();
  10333. var canvas = null;
  10334. Engine.Instances.push(this);
  10335. if (!canvasOrContext) {
  10336. return;
  10337. }
  10338. options = options || {};
  10339. if (canvasOrContext.getContext) {
  10340. canvas = canvasOrContext;
  10341. this._renderingCanvas = canvas;
  10342. if (antialias != null) {
  10343. options.antialias = antialias;
  10344. }
  10345. if (options.deterministicLockstep === undefined) {
  10346. options.deterministicLockstep = false;
  10347. }
  10348. if (options.lockstepMaxSteps === undefined) {
  10349. options.lockstepMaxSteps = 4;
  10350. }
  10351. if (options.preserveDrawingBuffer === undefined) {
  10352. options.preserveDrawingBuffer = false;
  10353. }
  10354. if (options.audioEngine === undefined) {
  10355. options.audioEngine = true;
  10356. }
  10357. if (options.stencil === undefined) {
  10358. options.stencil = true;
  10359. }
  10360. this._deterministicLockstep = options.deterministicLockstep;
  10361. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10362. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10363. // Exceptions
  10364. if (navigator && navigator.userAgent) {
  10365. var ua = navigator.userAgent;
  10366. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10367. var exception = _a[_i];
  10368. var key = exception.key;
  10369. var targets = exception.targets;
  10370. if (ua.indexOf(key) > -1) {
  10371. if (exception.capture && exception.captureConstraint) {
  10372. var capture = exception.capture;
  10373. var constraint = exception.captureConstraint;
  10374. var regex = new RegExp(capture);
  10375. var matches = regex.exec(ua);
  10376. if (matches && matches.length > 0) {
  10377. var capturedValue = parseInt(matches[matches.length - 1]);
  10378. if (capturedValue >= constraint) {
  10379. continue;
  10380. }
  10381. }
  10382. }
  10383. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10384. var target = targets_1[_b];
  10385. switch (target) {
  10386. case "uniformBuffer":
  10387. this.disableUniformBuffers = true;
  10388. break;
  10389. case "textureBindingOptimization":
  10390. this.disableTextureBindingOptimization = true;
  10391. break;
  10392. }
  10393. }
  10394. break;
  10395. }
  10396. }
  10397. }
  10398. // GL
  10399. if (!options.disableWebGL2Support) {
  10400. try {
  10401. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10402. if (this._gl) {
  10403. this._webGLVersion = 2.0;
  10404. }
  10405. }
  10406. catch (e) {
  10407. // Do nothing
  10408. }
  10409. }
  10410. if (!this._gl) {
  10411. if (!canvas) {
  10412. throw new Error("The provided canvas is null or undefined.");
  10413. }
  10414. try {
  10415. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10416. }
  10417. catch (e) {
  10418. throw new Error("WebGL not supported");
  10419. }
  10420. }
  10421. if (!this._gl) {
  10422. throw new Error("WebGL not supported");
  10423. }
  10424. this._onCanvasFocus = function () {
  10425. _this.onCanvasFocusObservable.notifyObservers(_this);
  10426. };
  10427. this._onCanvasBlur = function () {
  10428. _this.onCanvasBlurObservable.notifyObservers(_this);
  10429. };
  10430. canvas.addEventListener("focus", this._onCanvasFocus);
  10431. canvas.addEventListener("blur", this._onCanvasBlur);
  10432. this._onBlur = function () {
  10433. if (_this.disablePerformanceMonitorInBackground) {
  10434. _this._performanceMonitor.disable();
  10435. }
  10436. _this._windowIsBackground = true;
  10437. };
  10438. this._onFocus = function () {
  10439. if (_this.disablePerformanceMonitorInBackground) {
  10440. _this._performanceMonitor.enable();
  10441. }
  10442. _this._windowIsBackground = false;
  10443. };
  10444. this._onCanvasPointerOut = function () {
  10445. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  10446. };
  10447. window.addEventListener("blur", this._onBlur);
  10448. window.addEventListener("focus", this._onFocus);
  10449. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10450. // Context lost
  10451. if (!this._doNotHandleContextLost) {
  10452. this._onContextLost = function (evt) {
  10453. evt.preventDefault();
  10454. _this._contextWasLost = true;
  10455. BABYLON.Tools.Warn("WebGL context lost.");
  10456. _this.onContextLostObservable.notifyObservers(_this);
  10457. };
  10458. this._onContextRestored = function (evt) {
  10459. // Adding a timeout to avoid race condition at browser level
  10460. setTimeout(function () {
  10461. // Rebuild gl context
  10462. _this._initGLContext();
  10463. // Rebuild effects
  10464. _this._rebuildEffects();
  10465. // Rebuild textures
  10466. _this._rebuildInternalTextures();
  10467. // Rebuild buffers
  10468. _this._rebuildBuffers();
  10469. // Cache
  10470. _this.wipeCaches(true);
  10471. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10472. _this.onContextRestoredObservable.notifyObservers(_this);
  10473. _this._contextWasLost = false;
  10474. }, 0);
  10475. };
  10476. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10477. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10478. }
  10479. }
  10480. else {
  10481. this._gl = canvasOrContext;
  10482. this._renderingCanvas = this._gl.canvas;
  10483. if (this._gl.renderbufferStorageMultisample) {
  10484. this._webGLVersion = 2.0;
  10485. }
  10486. options.stencil = this._gl.getContextAttributes().stencil;
  10487. }
  10488. // Viewport
  10489. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10490. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10491. this.resize();
  10492. this._isStencilEnable = options.stencil ? true : false;
  10493. this._initGLContext();
  10494. if (canvas) {
  10495. // Fullscreen
  10496. this._onFullscreenChange = function () {
  10497. if (document.fullscreen !== undefined) {
  10498. _this.isFullscreen = document.fullscreen;
  10499. }
  10500. else if (document.mozFullScreen !== undefined) {
  10501. _this.isFullscreen = document.mozFullScreen;
  10502. }
  10503. else if (document.webkitIsFullScreen !== undefined) {
  10504. _this.isFullscreen = document.webkitIsFullScreen;
  10505. }
  10506. else if (document.msIsFullScreen !== undefined) {
  10507. _this.isFullscreen = document.msIsFullScreen;
  10508. }
  10509. // Pointer lock
  10510. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10511. canvas.requestPointerLock = canvas.requestPointerLock ||
  10512. canvas.msRequestPointerLock ||
  10513. canvas.mozRequestPointerLock ||
  10514. canvas.webkitRequestPointerLock;
  10515. if (canvas.requestPointerLock) {
  10516. canvas.requestPointerLock();
  10517. }
  10518. }
  10519. };
  10520. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10521. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10522. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10523. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10524. // Pointer lock
  10525. this._onPointerLockChange = function () {
  10526. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10527. document.webkitPointerLockElement === canvas ||
  10528. document.msPointerLockElement === canvas ||
  10529. document.pointerLockElement === canvas);
  10530. };
  10531. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10532. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10533. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10534. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10535. this._onVRDisplayPointerRestricted = function () {
  10536. if (canvas) {
  10537. canvas.requestPointerLock();
  10538. }
  10539. };
  10540. this._onVRDisplayPointerUnrestricted = function () {
  10541. document.exitPointerLock();
  10542. };
  10543. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10544. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10545. }
  10546. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10547. Engine.audioEngine = new BABYLON.AudioEngine();
  10548. }
  10549. // Prepare buffer pointers
  10550. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10551. this._currentBufferPointers[i] = new BufferPointer();
  10552. }
  10553. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10554. // Load WebVR Devices
  10555. if (options.autoEnableWebVR) {
  10556. this.initWebVR();
  10557. }
  10558. // Detect if we are running on a faulty buggy OS.
  10559. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10560. // Detect if we are running on a faulty buggy desktop OS.
  10561. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10562. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10563. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10564. }
  10565. Object.defineProperty(Engine, "LastCreatedEngine", {
  10566. get: function () {
  10567. if (Engine.Instances.length === 0) {
  10568. return null;
  10569. }
  10570. return Engine.Instances[Engine.Instances.length - 1];
  10571. },
  10572. enumerable: true,
  10573. configurable: true
  10574. });
  10575. Object.defineProperty(Engine, "LastCreatedScene", {
  10576. get: function () {
  10577. var lastCreatedEngine = Engine.LastCreatedEngine;
  10578. if (!lastCreatedEngine) {
  10579. return null;
  10580. }
  10581. if (lastCreatedEngine.scenes.length === 0) {
  10582. return null;
  10583. }
  10584. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10585. },
  10586. enumerable: true,
  10587. configurable: true
  10588. });
  10589. /**
  10590. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10591. */
  10592. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10593. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10594. var engine = Engine.Instances[engineIndex];
  10595. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10596. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10597. }
  10598. }
  10599. };
  10600. Object.defineProperty(Engine, "NEVER", {
  10601. get: function () {
  10602. return Engine._NEVER;
  10603. },
  10604. enumerable: true,
  10605. configurable: true
  10606. });
  10607. Object.defineProperty(Engine, "ALWAYS", {
  10608. get: function () {
  10609. return Engine._ALWAYS;
  10610. },
  10611. enumerable: true,
  10612. configurable: true
  10613. });
  10614. Object.defineProperty(Engine, "LESS", {
  10615. get: function () {
  10616. return Engine._LESS;
  10617. },
  10618. enumerable: true,
  10619. configurable: true
  10620. });
  10621. Object.defineProperty(Engine, "EQUAL", {
  10622. get: function () {
  10623. return Engine._EQUAL;
  10624. },
  10625. enumerable: true,
  10626. configurable: true
  10627. });
  10628. Object.defineProperty(Engine, "LEQUAL", {
  10629. get: function () {
  10630. return Engine._LEQUAL;
  10631. },
  10632. enumerable: true,
  10633. configurable: true
  10634. });
  10635. Object.defineProperty(Engine, "GREATER", {
  10636. get: function () {
  10637. return Engine._GREATER;
  10638. },
  10639. enumerable: true,
  10640. configurable: true
  10641. });
  10642. Object.defineProperty(Engine, "GEQUAL", {
  10643. get: function () {
  10644. return Engine._GEQUAL;
  10645. },
  10646. enumerable: true,
  10647. configurable: true
  10648. });
  10649. Object.defineProperty(Engine, "NOTEQUAL", {
  10650. get: function () {
  10651. return Engine._NOTEQUAL;
  10652. },
  10653. enumerable: true,
  10654. configurable: true
  10655. });
  10656. Object.defineProperty(Engine, "KEEP", {
  10657. get: function () {
  10658. return Engine._KEEP;
  10659. },
  10660. enumerable: true,
  10661. configurable: true
  10662. });
  10663. Object.defineProperty(Engine, "REPLACE", {
  10664. get: function () {
  10665. return Engine._REPLACE;
  10666. },
  10667. enumerable: true,
  10668. configurable: true
  10669. });
  10670. Object.defineProperty(Engine, "INCR", {
  10671. get: function () {
  10672. return Engine._INCR;
  10673. },
  10674. enumerable: true,
  10675. configurable: true
  10676. });
  10677. Object.defineProperty(Engine, "DECR", {
  10678. get: function () {
  10679. return Engine._DECR;
  10680. },
  10681. enumerable: true,
  10682. configurable: true
  10683. });
  10684. Object.defineProperty(Engine, "INVERT", {
  10685. get: function () {
  10686. return Engine._INVERT;
  10687. },
  10688. enumerable: true,
  10689. configurable: true
  10690. });
  10691. Object.defineProperty(Engine, "INCR_WRAP", {
  10692. get: function () {
  10693. return Engine._INCR_WRAP;
  10694. },
  10695. enumerable: true,
  10696. configurable: true
  10697. });
  10698. Object.defineProperty(Engine, "DECR_WRAP", {
  10699. get: function () {
  10700. return Engine._DECR_WRAP;
  10701. },
  10702. enumerable: true,
  10703. configurable: true
  10704. });
  10705. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10706. get: function () {
  10707. return Engine._ALPHA_DISABLE;
  10708. },
  10709. enumerable: true,
  10710. configurable: true
  10711. });
  10712. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10713. get: function () {
  10714. return Engine._ALPHA_ONEONE;
  10715. },
  10716. enumerable: true,
  10717. configurable: true
  10718. });
  10719. Object.defineProperty(Engine, "ALPHA_ADD", {
  10720. get: function () {
  10721. return Engine._ALPHA_ADD;
  10722. },
  10723. enumerable: true,
  10724. configurable: true
  10725. });
  10726. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10727. get: function () {
  10728. return Engine._ALPHA_COMBINE;
  10729. },
  10730. enumerable: true,
  10731. configurable: true
  10732. });
  10733. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10734. get: function () {
  10735. return Engine._ALPHA_SUBTRACT;
  10736. },
  10737. enumerable: true,
  10738. configurable: true
  10739. });
  10740. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10741. get: function () {
  10742. return Engine._ALPHA_MULTIPLY;
  10743. },
  10744. enumerable: true,
  10745. configurable: true
  10746. });
  10747. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10748. get: function () {
  10749. return Engine._ALPHA_MAXIMIZED;
  10750. },
  10751. enumerable: true,
  10752. configurable: true
  10753. });
  10754. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10755. get: function () {
  10756. return Engine._ALPHA_PREMULTIPLIED;
  10757. },
  10758. enumerable: true,
  10759. configurable: true
  10760. });
  10761. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10762. get: function () {
  10763. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10764. },
  10765. enumerable: true,
  10766. configurable: true
  10767. });
  10768. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10769. get: function () {
  10770. return Engine._ALPHA_INTERPOLATE;
  10771. },
  10772. enumerable: true,
  10773. configurable: true
  10774. });
  10775. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10776. get: function () {
  10777. return Engine._ALPHA_SCREENMODE;
  10778. },
  10779. enumerable: true,
  10780. configurable: true
  10781. });
  10782. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10783. get: function () {
  10784. return Engine._DELAYLOADSTATE_NONE;
  10785. },
  10786. enumerable: true,
  10787. configurable: true
  10788. });
  10789. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10790. get: function () {
  10791. return Engine._DELAYLOADSTATE_LOADED;
  10792. },
  10793. enumerable: true,
  10794. configurable: true
  10795. });
  10796. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10797. get: function () {
  10798. return Engine._DELAYLOADSTATE_LOADING;
  10799. },
  10800. enumerable: true,
  10801. configurable: true
  10802. });
  10803. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10804. get: function () {
  10805. return Engine._DELAYLOADSTATE_NOTLOADED;
  10806. },
  10807. enumerable: true,
  10808. configurable: true
  10809. });
  10810. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10811. get: function () {
  10812. return Engine._TEXTUREFORMAT_ALPHA;
  10813. },
  10814. enumerable: true,
  10815. configurable: true
  10816. });
  10817. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10818. get: function () {
  10819. return Engine._TEXTUREFORMAT_LUMINANCE;
  10820. },
  10821. enumerable: true,
  10822. configurable: true
  10823. });
  10824. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10825. /**
  10826. * R32F
  10827. */
  10828. get: function () {
  10829. return Engine._TEXTUREFORMAT_R32F;
  10830. },
  10831. enumerable: true,
  10832. configurable: true
  10833. });
  10834. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10835. /**
  10836. * RG32F
  10837. */
  10838. get: function () {
  10839. return Engine._TEXTUREFORMAT_RG32F;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10845. /**
  10846. * RGB32F
  10847. */
  10848. get: function () {
  10849. return Engine._TEXTUREFORMAT_RGB32F;
  10850. },
  10851. enumerable: true,
  10852. configurable: true
  10853. });
  10854. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  10855. /**
  10856. * RGBA32F
  10857. */
  10858. get: function () {
  10859. return Engine._TEXTUREFORMAT_RGBA32F;
  10860. },
  10861. enumerable: true,
  10862. configurable: true
  10863. });
  10864. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10865. get: function () {
  10866. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10872. get: function () {
  10873. return Engine._TEXTUREFORMAT_RGB;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10879. get: function () {
  10880. return Engine._TEXTUREFORMAT_RGBA;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10886. get: function () {
  10887. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10888. },
  10889. enumerable: true,
  10890. configurable: true
  10891. });
  10892. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10893. get: function () {
  10894. return Engine._TEXTURETYPE_FLOAT;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10900. get: function () {
  10901. return Engine._TEXTURETYPE_HALF_FLOAT;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10907. get: function () {
  10908. return Engine._SCALEMODE_FLOOR;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10914. get: function () {
  10915. return Engine._SCALEMODE_NEAREST;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10921. get: function () {
  10922. return Engine._SCALEMODE_CEILING;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(Engine, "Version", {
  10928. get: function () {
  10929. return "3.2.0-alpha8";
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10935. get: function () {
  10936. return this._vrExclusivePointerMode;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10942. get: function () {
  10943. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10944. },
  10945. enumerable: true,
  10946. configurable: true
  10947. });
  10948. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10949. get: function () {
  10950. return this._webGLVersion < 2 || this.forcePOTTextures;
  10951. },
  10952. enumerable: true,
  10953. configurable: true
  10954. });
  10955. Object.defineProperty(Engine.prototype, "badOS", {
  10956. get: function () {
  10957. return this._badOS;
  10958. },
  10959. enumerable: true,
  10960. configurable: true
  10961. });
  10962. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10963. get: function () {
  10964. return this._badDesktopOS;
  10965. },
  10966. enumerable: true,
  10967. configurable: true
  10968. });
  10969. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10970. get: function () {
  10971. return this._performanceMonitor;
  10972. },
  10973. enumerable: true,
  10974. configurable: true
  10975. });
  10976. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10977. get: function () {
  10978. return this._texturesSupported;
  10979. },
  10980. enumerable: true,
  10981. configurable: true
  10982. });
  10983. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10984. get: function () {
  10985. return this._textureFormatInUse;
  10986. },
  10987. enumerable: true,
  10988. configurable: true
  10989. });
  10990. Object.defineProperty(Engine.prototype, "currentViewport", {
  10991. get: function () {
  10992. return this._cachedViewport;
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10998. // Empty texture
  10999. get: function () {
  11000. if (!this._emptyTexture) {
  11001. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11002. }
  11003. return this._emptyTexture;
  11004. },
  11005. enumerable: true,
  11006. configurable: true
  11007. });
  11008. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11009. get: function () {
  11010. if (!this._emptyTexture3D) {
  11011. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11012. }
  11013. return this._emptyTexture3D;
  11014. },
  11015. enumerable: true,
  11016. configurable: true
  11017. });
  11018. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11019. get: function () {
  11020. if (!this._emptyCubeTexture) {
  11021. var faceData = new Uint8Array(4);
  11022. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11023. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11024. }
  11025. return this._emptyCubeTexture;
  11026. },
  11027. enumerable: true,
  11028. configurable: true
  11029. });
  11030. Engine.prototype._rebuildInternalTextures = function () {
  11031. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11032. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11033. var internalTexture = currentState_1[_i];
  11034. internalTexture._rebuild();
  11035. }
  11036. };
  11037. Engine.prototype._rebuildEffects = function () {
  11038. for (var key in this._compiledEffects) {
  11039. var effect = this._compiledEffects[key];
  11040. effect._prepareEffect();
  11041. }
  11042. BABYLON.Effect.ResetCache();
  11043. };
  11044. Engine.prototype._rebuildBuffers = function () {
  11045. // Index / Vertex
  11046. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11047. var scene = _a[_i];
  11048. scene.resetCachedMaterial();
  11049. scene._rebuildGeometries();
  11050. scene._rebuildTextures();
  11051. }
  11052. // Uniforms
  11053. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11054. var uniformBuffer = _c[_b];
  11055. uniformBuffer._rebuild();
  11056. }
  11057. };
  11058. Engine.prototype._initGLContext = function () {
  11059. // Caps
  11060. this._caps = new EngineCapabilities();
  11061. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11062. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11063. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11064. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11065. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11066. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11067. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11068. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11069. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11070. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11071. // Infos
  11072. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11073. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11074. if (rendererInfo != null) {
  11075. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11076. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11077. }
  11078. if (!this._glVendor) {
  11079. this._glVendor = "Unknown vendor";
  11080. }
  11081. if (!this._glRenderer) {
  11082. this._glRenderer = "Unknown renderer";
  11083. }
  11084. // Constants
  11085. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11086. if (this._gl.RGBA16F !== 0x881A) {
  11087. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11088. }
  11089. if (this._gl.RGBA32F !== 0x8814) {
  11090. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11091. }
  11092. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11093. this._gl.DEPTH24_STENCIL8 = 35056;
  11094. }
  11095. // Extensions
  11096. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11097. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11098. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11099. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11100. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11101. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11102. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11103. 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');
  11104. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11105. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11106. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11107. this._caps.highPrecisionShaderSupported = true;
  11108. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11109. if (this._caps.timerQuery) {
  11110. if (this._webGLVersion === 1) {
  11111. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11112. }
  11113. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11114. }
  11115. // Checks if some of the format renders first to allow the use of webgl inspector.
  11116. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11117. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11118. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11119. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11120. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11121. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11122. if (this._webGLVersion > 1) {
  11123. this._gl.HALF_FLOAT_OES = 0x140B;
  11124. }
  11125. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11126. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11127. // Draw buffers
  11128. if (this._webGLVersion > 1) {
  11129. this._caps.drawBuffersExtension = true;
  11130. }
  11131. else {
  11132. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11133. if (drawBuffersExtension !== null) {
  11134. this._caps.drawBuffersExtension = true;
  11135. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11136. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11137. for (var i = 0; i < 16; i++) {
  11138. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11139. }
  11140. }
  11141. else {
  11142. this._caps.drawBuffersExtension = false;
  11143. }
  11144. }
  11145. // Depth Texture
  11146. if (this._webGLVersion > 1) {
  11147. this._caps.depthTextureExtension = true;
  11148. }
  11149. else {
  11150. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11151. if (depthTextureExtension != null) {
  11152. this._caps.depthTextureExtension = true;
  11153. }
  11154. }
  11155. // Vertex array object
  11156. if (this._webGLVersion > 1) {
  11157. this._caps.vertexArrayObject = true;
  11158. }
  11159. else {
  11160. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11161. if (vertexArrayObjectExtension != null) {
  11162. this._caps.vertexArrayObject = true;
  11163. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11164. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11165. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11166. }
  11167. else {
  11168. this._caps.vertexArrayObject = false;
  11169. }
  11170. }
  11171. // Instances count
  11172. if (this._webGLVersion > 1) {
  11173. this._caps.instancedArrays = true;
  11174. }
  11175. else {
  11176. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11177. if (instanceExtension != null) {
  11178. this._caps.instancedArrays = true;
  11179. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11180. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11181. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11182. }
  11183. else {
  11184. this._caps.instancedArrays = false;
  11185. }
  11186. }
  11187. // Intelligently add supported compressed formats in order to check for.
  11188. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11189. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11190. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11191. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11192. if (this._caps.astc)
  11193. this.texturesSupported.push('-astc.ktx');
  11194. if (this._caps.s3tc)
  11195. this.texturesSupported.push('-dxt.ktx');
  11196. if (this._caps.pvrtc)
  11197. this.texturesSupported.push('-pvrtc.ktx');
  11198. if (this._caps.etc2)
  11199. this.texturesSupported.push('-etc2.ktx');
  11200. if (this._caps.etc1)
  11201. this.texturesSupported.push('-etc1.ktx');
  11202. if (this._gl.getShaderPrecisionFormat) {
  11203. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11204. if (highp) {
  11205. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11206. }
  11207. }
  11208. // Depth buffer
  11209. this.setDepthBuffer(true);
  11210. this.setDepthFunctionToLessOrEqual();
  11211. this.setDepthWrite(true);
  11212. // Texture maps
  11213. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11214. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11215. this._nextFreeTextureSlots.push(slot);
  11216. }
  11217. };
  11218. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11219. get: function () {
  11220. return this._webGLVersion;
  11221. },
  11222. enumerable: true,
  11223. configurable: true
  11224. });
  11225. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11226. /**
  11227. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11228. */
  11229. get: function () {
  11230. return this._isStencilEnable;
  11231. },
  11232. enumerable: true,
  11233. configurable: true
  11234. });
  11235. Engine.prototype._prepareWorkingCanvas = function () {
  11236. if (this._workingCanvas) {
  11237. return;
  11238. }
  11239. this._workingCanvas = document.createElement("canvas");
  11240. var context = this._workingCanvas.getContext("2d");
  11241. if (context) {
  11242. this._workingContext = context;
  11243. }
  11244. };
  11245. Engine.prototype.resetTextureCache = function () {
  11246. for (var key in this._boundTexturesCache) {
  11247. var boundTexture = this._boundTexturesCache[key];
  11248. if (boundTexture) {
  11249. this._removeDesignatedSlot(boundTexture);
  11250. }
  11251. this._boundTexturesCache[key] = null;
  11252. }
  11253. if (!this.disableTextureBindingOptimization) {
  11254. this._nextFreeTextureSlots = [];
  11255. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11256. this._nextFreeTextureSlots.push(slot);
  11257. }
  11258. }
  11259. this._currentTextureChannel = -1;
  11260. };
  11261. Engine.prototype.isDeterministicLockStep = function () {
  11262. return this._deterministicLockstep;
  11263. };
  11264. Engine.prototype.getLockstepMaxSteps = function () {
  11265. return this._lockstepMaxSteps;
  11266. };
  11267. Engine.prototype.getGlInfo = function () {
  11268. return {
  11269. vendor: this._glVendor,
  11270. renderer: this._glRenderer,
  11271. version: this._glVersion
  11272. };
  11273. };
  11274. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11275. if (useScreen === void 0) { useScreen = false; }
  11276. var viewport = camera.viewport;
  11277. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11278. };
  11279. Engine.prototype.getRenderWidth = function (useScreen) {
  11280. if (useScreen === void 0) { useScreen = false; }
  11281. if (!useScreen && this._currentRenderTarget) {
  11282. return this._currentRenderTarget.width;
  11283. }
  11284. return this._gl.drawingBufferWidth;
  11285. };
  11286. Engine.prototype.getRenderHeight = function (useScreen) {
  11287. if (useScreen === void 0) { useScreen = false; }
  11288. if (!useScreen && this._currentRenderTarget) {
  11289. return this._currentRenderTarget.height;
  11290. }
  11291. return this._gl.drawingBufferHeight;
  11292. };
  11293. Engine.prototype.getRenderingCanvas = function () {
  11294. return this._renderingCanvas;
  11295. };
  11296. Engine.prototype.getRenderingCanvasClientRect = function () {
  11297. if (!this._renderingCanvas) {
  11298. return null;
  11299. }
  11300. return this._renderingCanvas.getBoundingClientRect();
  11301. };
  11302. Engine.prototype.setHardwareScalingLevel = function (level) {
  11303. this._hardwareScalingLevel = level;
  11304. this.resize();
  11305. };
  11306. Engine.prototype.getHardwareScalingLevel = function () {
  11307. return this._hardwareScalingLevel;
  11308. };
  11309. Engine.prototype.getLoadedTexturesCache = function () {
  11310. return this._internalTexturesCache;
  11311. };
  11312. Engine.prototype.getCaps = function () {
  11313. return this._caps;
  11314. };
  11315. Object.defineProperty(Engine.prototype, "drawCalls", {
  11316. /** The number of draw calls submitted last frame */
  11317. get: function () {
  11318. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11319. return 0;
  11320. },
  11321. enumerable: true,
  11322. configurable: true
  11323. });
  11324. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11325. get: function () {
  11326. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11327. return null;
  11328. },
  11329. enumerable: true,
  11330. configurable: true
  11331. });
  11332. Engine.prototype.getDepthFunction = function () {
  11333. return this._depthCullingState.depthFunc;
  11334. };
  11335. Engine.prototype.setDepthFunction = function (depthFunc) {
  11336. this._depthCullingState.depthFunc = depthFunc;
  11337. };
  11338. Engine.prototype.setDepthFunctionToGreater = function () {
  11339. this._depthCullingState.depthFunc = this._gl.GREATER;
  11340. };
  11341. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11342. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11343. };
  11344. Engine.prototype.setDepthFunctionToLess = function () {
  11345. this._depthCullingState.depthFunc = this._gl.LESS;
  11346. };
  11347. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11348. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11349. };
  11350. Engine.prototype.getStencilBuffer = function () {
  11351. return this._stencilState.stencilTest;
  11352. };
  11353. Engine.prototype.setStencilBuffer = function (enable) {
  11354. this._stencilState.stencilTest = enable;
  11355. };
  11356. Engine.prototype.getStencilMask = function () {
  11357. return this._stencilState.stencilMask;
  11358. };
  11359. Engine.prototype.setStencilMask = function (mask) {
  11360. this._stencilState.stencilMask = mask;
  11361. };
  11362. Engine.prototype.getStencilFunction = function () {
  11363. return this._stencilState.stencilFunc;
  11364. };
  11365. Engine.prototype.getStencilFunctionReference = function () {
  11366. return this._stencilState.stencilFuncRef;
  11367. };
  11368. Engine.prototype.getStencilFunctionMask = function () {
  11369. return this._stencilState.stencilFuncMask;
  11370. };
  11371. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11372. this._stencilState.stencilFunc = stencilFunc;
  11373. };
  11374. Engine.prototype.setStencilFunctionReference = function (reference) {
  11375. this._stencilState.stencilFuncRef = reference;
  11376. };
  11377. Engine.prototype.setStencilFunctionMask = function (mask) {
  11378. this._stencilState.stencilFuncMask = mask;
  11379. };
  11380. Engine.prototype.getStencilOperationFail = function () {
  11381. return this._stencilState.stencilOpStencilFail;
  11382. };
  11383. Engine.prototype.getStencilOperationDepthFail = function () {
  11384. return this._stencilState.stencilOpDepthFail;
  11385. };
  11386. Engine.prototype.getStencilOperationPass = function () {
  11387. return this._stencilState.stencilOpStencilDepthPass;
  11388. };
  11389. Engine.prototype.setStencilOperationFail = function (operation) {
  11390. this._stencilState.stencilOpStencilFail = operation;
  11391. };
  11392. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11393. this._stencilState.stencilOpDepthFail = operation;
  11394. };
  11395. Engine.prototype.setStencilOperationPass = function (operation) {
  11396. this._stencilState.stencilOpStencilDepthPass = operation;
  11397. };
  11398. Engine.prototype.setDitheringState = function (value) {
  11399. if (value) {
  11400. this._gl.enable(this._gl.DITHER);
  11401. }
  11402. else {
  11403. this._gl.disable(this._gl.DITHER);
  11404. }
  11405. };
  11406. Engine.prototype.setRasterizerState = function (value) {
  11407. if (value) {
  11408. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11409. }
  11410. else {
  11411. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11412. }
  11413. };
  11414. /**
  11415. * stop executing a render loop function and remove it from the execution array
  11416. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11417. */
  11418. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11419. if (!renderFunction) {
  11420. this._activeRenderLoops = [];
  11421. return;
  11422. }
  11423. var index = this._activeRenderLoops.indexOf(renderFunction);
  11424. if (index >= 0) {
  11425. this._activeRenderLoops.splice(index, 1);
  11426. }
  11427. };
  11428. Engine.prototype._renderLoop = function () {
  11429. if (!this._contextWasLost) {
  11430. var shouldRender = true;
  11431. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11432. shouldRender = false;
  11433. }
  11434. if (shouldRender) {
  11435. // Start new frame
  11436. this.beginFrame();
  11437. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11438. var renderFunction = this._activeRenderLoops[index];
  11439. renderFunction();
  11440. }
  11441. // Present
  11442. this.endFrame();
  11443. }
  11444. }
  11445. if (this._activeRenderLoops.length > 0) {
  11446. // Register new frame
  11447. var requester = null;
  11448. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11449. requester = this._vrDisplay;
  11450. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11451. }
  11452. else {
  11453. this._renderingQueueLaunched = false;
  11454. }
  11455. };
  11456. /**
  11457. * Register and execute a render loop. The engine can have more than one render function.
  11458. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11459. * @example
  11460. * engine.runRenderLoop(function () {
  11461. * scene.render()
  11462. * })
  11463. */
  11464. Engine.prototype.runRenderLoop = function (renderFunction) {
  11465. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11466. return;
  11467. }
  11468. this._activeRenderLoops.push(renderFunction);
  11469. if (!this._renderingQueueLaunched) {
  11470. this._renderingQueueLaunched = true;
  11471. this._bindedRenderFunction = this._renderLoop.bind(this);
  11472. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11473. }
  11474. };
  11475. /**
  11476. * Toggle full screen mode.
  11477. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11478. * @param {any} options - an options object to be sent to the requestFullscreen function
  11479. */
  11480. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11481. if (this.isFullscreen) {
  11482. BABYLON.Tools.ExitFullscreen();
  11483. }
  11484. else {
  11485. this._pointerLockRequested = requestPointerLock;
  11486. if (this._renderingCanvas) {
  11487. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11488. }
  11489. }
  11490. };
  11491. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11492. if (stencil === void 0) { stencil = false; }
  11493. this.applyStates();
  11494. var mode = 0;
  11495. if (backBuffer && color) {
  11496. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11497. mode |= this._gl.COLOR_BUFFER_BIT;
  11498. }
  11499. if (depth) {
  11500. this._gl.clearDepth(1.0);
  11501. mode |= this._gl.DEPTH_BUFFER_BIT;
  11502. }
  11503. if (stencil) {
  11504. this._gl.clearStencil(0);
  11505. mode |= this._gl.STENCIL_BUFFER_BIT;
  11506. }
  11507. this._gl.clear(mode);
  11508. };
  11509. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11510. var gl = this._gl;
  11511. // Save state
  11512. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11513. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11514. // Change state
  11515. gl.enable(gl.SCISSOR_TEST);
  11516. gl.scissor(x, y, width, height);
  11517. // Clear
  11518. this.clear(clearColor, true, true, true);
  11519. // Restore state
  11520. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11521. if (curScissor === true) {
  11522. gl.enable(gl.SCISSOR_TEST);
  11523. }
  11524. else {
  11525. gl.disable(gl.SCISSOR_TEST);
  11526. }
  11527. };
  11528. /**
  11529. * Set the WebGL's viewport
  11530. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11531. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11532. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11533. */
  11534. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11535. var width = requiredWidth || this.getRenderWidth();
  11536. var height = requiredHeight || this.getRenderHeight();
  11537. var x = viewport.x || 0;
  11538. var y = viewport.y || 0;
  11539. this._cachedViewport = viewport;
  11540. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11541. };
  11542. /**
  11543. * Directly set the WebGL Viewport
  11544. * The x, y, width & height are directly passed to the WebGL call
  11545. * @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.
  11546. */
  11547. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11548. var currentViewport = this._cachedViewport;
  11549. this._cachedViewport = null;
  11550. this._gl.viewport(x, y, width, height);
  11551. return currentViewport;
  11552. };
  11553. Engine.prototype.beginFrame = function () {
  11554. this.onBeginFrameObservable.notifyObservers(this);
  11555. this._measureFps();
  11556. };
  11557. Engine.prototype.endFrame = function () {
  11558. //force a flush in case we are using a bad OS.
  11559. if (this._badOS) {
  11560. this.flushFramebuffer();
  11561. }
  11562. //submit frame to the vr device, if enabled
  11563. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11564. // TODO: We should only submit the frame if we read frameData successfully.
  11565. this._vrDisplay.submitFrame();
  11566. }
  11567. this.onEndFrameObservable.notifyObservers(this);
  11568. };
  11569. /**
  11570. * resize the view according to the canvas' size.
  11571. * @example
  11572. * window.addEventListener("resize", function () {
  11573. * engine.resize();
  11574. * });
  11575. */
  11576. Engine.prototype.resize = function () {
  11577. // We're not resizing the size of the canvas while in VR mode & presenting
  11578. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11579. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11580. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11581. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11582. }
  11583. };
  11584. /**
  11585. * force a specific size of the canvas
  11586. * @param {number} width - the new canvas' width
  11587. * @param {number} height - the new canvas' height
  11588. */
  11589. Engine.prototype.setSize = function (width, height) {
  11590. if (!this._renderingCanvas) {
  11591. return;
  11592. }
  11593. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11594. return;
  11595. }
  11596. this._renderingCanvas.width = width;
  11597. this._renderingCanvas.height = height;
  11598. for (var index = 0; index < this.scenes.length; index++) {
  11599. var scene = this.scenes[index];
  11600. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11601. var cam = scene.cameras[camIndex];
  11602. cam._currentRenderId = 0;
  11603. }
  11604. }
  11605. if (this.onResizeObservable.hasObservers) {
  11606. this.onResizeObservable.notifyObservers(this);
  11607. }
  11608. };
  11609. // WebVR functions
  11610. Engine.prototype.isVRDevicePresent = function () {
  11611. return !!this._vrDisplay;
  11612. };
  11613. Engine.prototype.getVRDevice = function () {
  11614. return this._vrDisplay;
  11615. };
  11616. /**
  11617. * Initializes a webVR display and starts listening to display change events.
  11618. * The onVRDisplayChangedObservable will be notified upon these changes.
  11619. * @returns The onVRDisplayChangedObservable.
  11620. */
  11621. Engine.prototype.initWebVR = function () {
  11622. this.initWebVRAsync();
  11623. return this.onVRDisplayChangedObservable;
  11624. };
  11625. /**
  11626. * Initializes a webVR display and starts listening to display change events.
  11627. * The onVRDisplayChangedObservable will be notified upon these changes.
  11628. * @returns A promise containing a VRDisplay and if vr is supported.
  11629. */
  11630. Engine.prototype.initWebVRAsync = function () {
  11631. var _this = this;
  11632. var notifyObservers = function () {
  11633. var eventArgs = {
  11634. vrDisplay: _this._vrDisplay,
  11635. vrSupported: _this._vrSupported
  11636. };
  11637. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11638. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11639. };
  11640. if (!this._onVrDisplayConnect) {
  11641. this._onVrDisplayConnect = function (event) {
  11642. _this._vrDisplay = event.display;
  11643. notifyObservers();
  11644. };
  11645. this._onVrDisplayDisconnect = function () {
  11646. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11647. _this._vrDisplay = undefined;
  11648. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11649. notifyObservers();
  11650. };
  11651. this._onVrDisplayPresentChange = function () {
  11652. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11653. };
  11654. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11655. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11656. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11657. }
  11658. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11659. this._webVRInitPromise.then(notifyObservers);
  11660. return this._webVRInitPromise;
  11661. };
  11662. Engine.prototype.enableVR = function () {
  11663. var _this = this;
  11664. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11665. var onResolved = function () {
  11666. _this.onVRRequestPresentComplete.notifyObservers(true);
  11667. _this._onVRFullScreenTriggered();
  11668. };
  11669. var onRejected = function () {
  11670. _this.onVRRequestPresentComplete.notifyObservers(false);
  11671. };
  11672. this.onVRRequestPresentStart.notifyObservers(this);
  11673. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11674. }
  11675. };
  11676. Engine.prototype.disableVR = function () {
  11677. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11678. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11679. }
  11680. };
  11681. Engine.prototype._getVRDisplaysAsync = function () {
  11682. var _this = this;
  11683. return new Promise(function (res, rej) {
  11684. if (navigator.getVRDisplays) {
  11685. navigator.getVRDisplays().then(function (devices) {
  11686. _this._vrSupported = true;
  11687. // note that devices may actually be an empty array. This is fine;
  11688. // we expect this._vrDisplay to be undefined in this case.
  11689. _this._vrDisplay = devices[0];
  11690. res({
  11691. vrDisplay: _this._vrDisplay,
  11692. vrSupported: _this._vrSupported
  11693. });
  11694. });
  11695. }
  11696. else {
  11697. _this._vrDisplay = undefined;
  11698. _this._vrSupported = false;
  11699. res({
  11700. vrDisplay: _this._vrDisplay,
  11701. vrSupported: _this._vrSupported
  11702. });
  11703. }
  11704. });
  11705. };
  11706. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  11707. if (this._currentRenderTarget) {
  11708. this.unBindFramebuffer(this._currentRenderTarget);
  11709. }
  11710. this._currentRenderTarget = texture;
  11711. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11712. var gl = this._gl;
  11713. if (texture.isCube) {
  11714. if (faceIndex === undefined) {
  11715. faceIndex = 0;
  11716. }
  11717. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11718. }
  11719. if (this._cachedViewport && !forceFullscreenViewport) {
  11720. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11721. }
  11722. else {
  11723. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11724. }
  11725. this.wipeCaches();
  11726. };
  11727. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11728. if (this._currentFramebuffer !== framebuffer) {
  11729. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11730. this._currentFramebuffer = framebuffer;
  11731. }
  11732. };
  11733. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11734. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11735. this._currentRenderTarget = null;
  11736. // If MSAA, we need to bitblt back to main texture
  11737. var gl = this._gl;
  11738. if (texture._MSAAFramebuffer) {
  11739. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11740. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11741. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11742. }
  11743. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11744. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11745. gl.generateMipmap(gl.TEXTURE_2D);
  11746. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11747. }
  11748. if (onBeforeUnbind) {
  11749. if (texture._MSAAFramebuffer) {
  11750. // Bind the correct framebuffer
  11751. this.bindUnboundFramebuffer(texture._framebuffer);
  11752. }
  11753. onBeforeUnbind();
  11754. }
  11755. this.bindUnboundFramebuffer(null);
  11756. };
  11757. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11758. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11759. this._currentRenderTarget = null;
  11760. // If MSAA, we need to bitblt back to main texture
  11761. var gl = this._gl;
  11762. if (textures[0]._MSAAFramebuffer) {
  11763. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11764. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11765. var attachments = textures[0]._attachments;
  11766. if (!attachments) {
  11767. attachments = new Array(textures.length);
  11768. textures[0]._attachments = attachments;
  11769. }
  11770. for (var i = 0; i < textures.length; i++) {
  11771. var texture = textures[i];
  11772. for (var j = 0; j < attachments.length; j++) {
  11773. attachments[j] = gl.NONE;
  11774. }
  11775. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11776. gl.readBuffer(attachments[i]);
  11777. gl.drawBuffers(attachments);
  11778. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11779. }
  11780. for (var i = 0; i < attachments.length; i++) {
  11781. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11782. }
  11783. gl.drawBuffers(attachments);
  11784. }
  11785. for (var i = 0; i < textures.length; i++) {
  11786. var texture = textures[i];
  11787. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11788. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11789. gl.generateMipmap(gl.TEXTURE_2D);
  11790. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11791. }
  11792. }
  11793. if (onBeforeUnbind) {
  11794. if (textures[0]._MSAAFramebuffer) {
  11795. // Bind the correct framebuffer
  11796. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11797. }
  11798. onBeforeUnbind();
  11799. }
  11800. this.bindUnboundFramebuffer(null);
  11801. };
  11802. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11803. if (texture.generateMipMaps) {
  11804. var gl = this._gl;
  11805. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11806. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11807. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11808. }
  11809. };
  11810. Engine.prototype.flushFramebuffer = function () {
  11811. this._gl.flush();
  11812. };
  11813. Engine.prototype.restoreDefaultFramebuffer = function () {
  11814. if (this._currentRenderTarget) {
  11815. this.unBindFramebuffer(this._currentRenderTarget);
  11816. }
  11817. else {
  11818. this.bindUnboundFramebuffer(null);
  11819. }
  11820. if (this._cachedViewport) {
  11821. this.setViewport(this._cachedViewport);
  11822. }
  11823. this.wipeCaches();
  11824. };
  11825. // UBOs
  11826. Engine.prototype.createUniformBuffer = function (elements) {
  11827. var ubo = this._gl.createBuffer();
  11828. if (!ubo) {
  11829. throw new Error("Unable to create uniform buffer");
  11830. }
  11831. this.bindUniformBuffer(ubo);
  11832. if (elements instanceof Float32Array) {
  11833. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11834. }
  11835. else {
  11836. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11837. }
  11838. this.bindUniformBuffer(null);
  11839. ubo.references = 1;
  11840. return ubo;
  11841. };
  11842. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11843. var ubo = this._gl.createBuffer();
  11844. if (!ubo) {
  11845. throw new Error("Unable to create dynamic uniform buffer");
  11846. }
  11847. this.bindUniformBuffer(ubo);
  11848. if (elements instanceof Float32Array) {
  11849. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11850. }
  11851. else {
  11852. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11853. }
  11854. this.bindUniformBuffer(null);
  11855. ubo.references = 1;
  11856. return ubo;
  11857. };
  11858. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11859. this.bindUniformBuffer(uniformBuffer);
  11860. if (offset === undefined) {
  11861. offset = 0;
  11862. }
  11863. if (count === undefined) {
  11864. if (elements instanceof Float32Array) {
  11865. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11866. }
  11867. else {
  11868. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11869. }
  11870. }
  11871. else {
  11872. if (elements instanceof Float32Array) {
  11873. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11874. }
  11875. else {
  11876. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11877. }
  11878. }
  11879. this.bindUniformBuffer(null);
  11880. };
  11881. // VBOs
  11882. Engine.prototype._resetVertexBufferBinding = function () {
  11883. this.bindArrayBuffer(null);
  11884. this._cachedVertexBuffers = null;
  11885. };
  11886. Engine.prototype.createVertexBuffer = function (vertices) {
  11887. var vbo = this._gl.createBuffer();
  11888. if (!vbo) {
  11889. throw new Error("Unable to create vertex buffer");
  11890. }
  11891. this.bindArrayBuffer(vbo);
  11892. if (vertices instanceof Float32Array) {
  11893. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11894. }
  11895. else {
  11896. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11897. }
  11898. this._resetVertexBufferBinding();
  11899. vbo.references = 1;
  11900. return vbo;
  11901. };
  11902. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11903. var vbo = this._gl.createBuffer();
  11904. if (!vbo) {
  11905. throw new Error("Unable to create dynamic vertex buffer");
  11906. }
  11907. this.bindArrayBuffer(vbo);
  11908. if (vertices instanceof Float32Array) {
  11909. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11910. }
  11911. else {
  11912. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11913. }
  11914. this._resetVertexBufferBinding();
  11915. vbo.references = 1;
  11916. return vbo;
  11917. };
  11918. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11919. if (offset === void 0) { offset = 0; }
  11920. // Force cache update
  11921. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11922. this.bindIndexBuffer(indexBuffer);
  11923. var arrayBuffer;
  11924. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11925. arrayBuffer = indices;
  11926. }
  11927. else {
  11928. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11929. }
  11930. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11931. this._resetIndexBufferBinding();
  11932. };
  11933. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11934. this.bindArrayBuffer(vertexBuffer);
  11935. if (offset === undefined) {
  11936. offset = 0;
  11937. }
  11938. if (count === undefined) {
  11939. if (vertices instanceof Float32Array) {
  11940. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11941. }
  11942. else {
  11943. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11944. }
  11945. }
  11946. else {
  11947. if (vertices instanceof Float32Array) {
  11948. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11949. }
  11950. else {
  11951. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11952. }
  11953. }
  11954. this._resetVertexBufferBinding();
  11955. };
  11956. Engine.prototype._resetIndexBufferBinding = function () {
  11957. this.bindIndexBuffer(null);
  11958. this._cachedIndexBuffer = null;
  11959. };
  11960. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11961. var vbo = this._gl.createBuffer();
  11962. if (!vbo) {
  11963. throw new Error("Unable to create index buffer");
  11964. }
  11965. this.bindIndexBuffer(vbo);
  11966. // Check for 32 bits indices
  11967. var arrayBuffer;
  11968. var need32Bits = false;
  11969. if (indices instanceof Uint16Array) {
  11970. arrayBuffer = indices;
  11971. }
  11972. else {
  11973. //check 32 bit support
  11974. if (this._caps.uintIndices) {
  11975. if (indices instanceof Uint32Array) {
  11976. arrayBuffer = indices;
  11977. need32Bits = true;
  11978. }
  11979. else {
  11980. //number[] or Int32Array, check if 32 bit is necessary
  11981. for (var index = 0; index < indices.length; index++) {
  11982. if (indices[index] > 65535) {
  11983. need32Bits = true;
  11984. break;
  11985. }
  11986. }
  11987. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11988. }
  11989. }
  11990. else {
  11991. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11992. arrayBuffer = new Uint16Array(indices);
  11993. }
  11994. }
  11995. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11996. this._resetIndexBufferBinding();
  11997. vbo.references = 1;
  11998. vbo.is32Bits = need32Bits;
  11999. return vbo;
  12000. };
  12001. Engine.prototype.bindArrayBuffer = function (buffer) {
  12002. if (!this._vaoRecordInProgress) {
  12003. this._unbindVertexArrayObject();
  12004. }
  12005. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12006. };
  12007. Engine.prototype.bindUniformBuffer = function (buffer) {
  12008. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12009. };
  12010. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12011. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12012. };
  12013. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12014. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12015. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12016. };
  12017. ;
  12018. Engine.prototype.bindIndexBuffer = function (buffer) {
  12019. if (!this._vaoRecordInProgress) {
  12020. this._unbindVertexArrayObject();
  12021. }
  12022. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12023. };
  12024. Engine.prototype.bindBuffer = function (buffer, target) {
  12025. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12026. this._gl.bindBuffer(target, buffer);
  12027. this._currentBoundBuffer[target] = buffer;
  12028. }
  12029. };
  12030. Engine.prototype.updateArrayBuffer = function (data) {
  12031. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12032. };
  12033. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12034. var pointer = this._currentBufferPointers[indx];
  12035. var changed = false;
  12036. if (!pointer.active) {
  12037. changed = true;
  12038. pointer.active = true;
  12039. pointer.index = indx;
  12040. pointer.size = size;
  12041. pointer.type = type;
  12042. pointer.normalized = normalized;
  12043. pointer.stride = stride;
  12044. pointer.offset = offset;
  12045. pointer.buffer = buffer;
  12046. }
  12047. else {
  12048. if (pointer.buffer !== buffer) {
  12049. pointer.buffer = buffer;
  12050. changed = true;
  12051. }
  12052. if (pointer.size !== size) {
  12053. pointer.size = size;
  12054. changed = true;
  12055. }
  12056. if (pointer.type !== type) {
  12057. pointer.type = type;
  12058. changed = true;
  12059. }
  12060. if (pointer.normalized !== normalized) {
  12061. pointer.normalized = normalized;
  12062. changed = true;
  12063. }
  12064. if (pointer.stride !== stride) {
  12065. pointer.stride = stride;
  12066. changed = true;
  12067. }
  12068. if (pointer.offset !== offset) {
  12069. pointer.offset = offset;
  12070. changed = true;
  12071. }
  12072. }
  12073. if (changed || this._vaoRecordInProgress) {
  12074. this.bindArrayBuffer(buffer);
  12075. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12076. }
  12077. };
  12078. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12079. if (indexBuffer == null) {
  12080. return;
  12081. }
  12082. if (this._cachedIndexBuffer !== indexBuffer) {
  12083. this._cachedIndexBuffer = indexBuffer;
  12084. this.bindIndexBuffer(indexBuffer);
  12085. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12086. }
  12087. };
  12088. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12089. var attributes = effect.getAttributesNames();
  12090. if (!this._vaoRecordInProgress) {
  12091. this._unbindVertexArrayObject();
  12092. }
  12093. this.unbindAllAttributes();
  12094. for (var index = 0; index < attributes.length; index++) {
  12095. var order = effect.getAttributeLocation(index);
  12096. if (order >= 0) {
  12097. var vertexBuffer = vertexBuffers[attributes[index]];
  12098. if (!vertexBuffer) {
  12099. continue;
  12100. }
  12101. this._gl.enableVertexAttribArray(order);
  12102. if (!this._vaoRecordInProgress) {
  12103. this._vertexAttribArraysEnabled[order] = true;
  12104. }
  12105. var buffer = vertexBuffer.getBuffer();
  12106. if (buffer) {
  12107. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12108. if (vertexBuffer.getIsInstanced()) {
  12109. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12110. if (!this._vaoRecordInProgress) {
  12111. this._currentInstanceLocations.push(order);
  12112. this._currentInstanceBuffers.push(buffer);
  12113. }
  12114. }
  12115. }
  12116. }
  12117. }
  12118. };
  12119. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12120. var vao = this._gl.createVertexArray();
  12121. this._vaoRecordInProgress = true;
  12122. this._gl.bindVertexArray(vao);
  12123. this._mustWipeVertexAttributes = true;
  12124. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12125. this.bindIndexBuffer(indexBuffer);
  12126. this._vaoRecordInProgress = false;
  12127. this._gl.bindVertexArray(null);
  12128. return vao;
  12129. };
  12130. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12131. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12132. this._cachedVertexArrayObject = vertexArrayObject;
  12133. this._gl.bindVertexArray(vertexArrayObject);
  12134. this._cachedVertexBuffers = null;
  12135. this._cachedIndexBuffer = null;
  12136. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12137. this._mustWipeVertexAttributes = true;
  12138. }
  12139. };
  12140. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12141. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12142. this._cachedVertexBuffers = vertexBuffer;
  12143. this._cachedEffectForVertexBuffers = effect;
  12144. var attributesCount = effect.getAttributesCount();
  12145. this._unbindVertexArrayObject();
  12146. this.unbindAllAttributes();
  12147. var offset = 0;
  12148. for (var index = 0; index < attributesCount; index++) {
  12149. if (index < vertexDeclaration.length) {
  12150. var order = effect.getAttributeLocation(index);
  12151. if (order >= 0) {
  12152. this._gl.enableVertexAttribArray(order);
  12153. this._vertexAttribArraysEnabled[order] = true;
  12154. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12155. }
  12156. offset += vertexDeclaration[index] * 4;
  12157. }
  12158. }
  12159. }
  12160. this._bindIndexBufferWithCache(indexBuffer);
  12161. };
  12162. Engine.prototype._unbindVertexArrayObject = function () {
  12163. if (!this._cachedVertexArrayObject) {
  12164. return;
  12165. }
  12166. this._cachedVertexArrayObject = null;
  12167. this._gl.bindVertexArray(null);
  12168. };
  12169. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12170. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12171. this._cachedVertexBuffers = vertexBuffers;
  12172. this._cachedEffectForVertexBuffers = effect;
  12173. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12174. }
  12175. this._bindIndexBufferWithCache(indexBuffer);
  12176. };
  12177. Engine.prototype.unbindInstanceAttributes = function () {
  12178. var boundBuffer;
  12179. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12180. var instancesBuffer = this._currentInstanceBuffers[i];
  12181. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12182. boundBuffer = instancesBuffer;
  12183. this.bindArrayBuffer(instancesBuffer);
  12184. }
  12185. var offsetLocation = this._currentInstanceLocations[i];
  12186. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12187. }
  12188. this._currentInstanceBuffers.length = 0;
  12189. this._currentInstanceLocations.length = 0;
  12190. };
  12191. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12192. this._gl.deleteVertexArray(vao);
  12193. };
  12194. Engine.prototype._releaseBuffer = function (buffer) {
  12195. buffer.references--;
  12196. if (buffer.references === 0) {
  12197. this._gl.deleteBuffer(buffer);
  12198. return true;
  12199. }
  12200. return false;
  12201. };
  12202. Engine.prototype.createInstancesBuffer = function (capacity) {
  12203. var buffer = this._gl.createBuffer();
  12204. if (!buffer) {
  12205. throw new Error("Unable to create instance buffer");
  12206. }
  12207. buffer.capacity = capacity;
  12208. this.bindArrayBuffer(buffer);
  12209. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12210. return buffer;
  12211. };
  12212. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12213. this._gl.deleteBuffer(buffer);
  12214. };
  12215. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12216. this.bindArrayBuffer(instancesBuffer);
  12217. if (data) {
  12218. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12219. }
  12220. if (offsetLocations[0].index !== undefined) {
  12221. var stride = 0;
  12222. for (var i = 0; i < offsetLocations.length; i++) {
  12223. var ai = offsetLocations[i];
  12224. stride += ai.attributeSize * 4;
  12225. }
  12226. for (var i = 0; i < offsetLocations.length; i++) {
  12227. var ai = offsetLocations[i];
  12228. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12229. this._gl.enableVertexAttribArray(ai.index);
  12230. this._vertexAttribArraysEnabled[ai.index] = true;
  12231. }
  12232. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12233. this._gl.vertexAttribDivisor(ai.index, 1);
  12234. this._currentInstanceLocations.push(ai.index);
  12235. this._currentInstanceBuffers.push(instancesBuffer);
  12236. }
  12237. }
  12238. else {
  12239. for (var index = 0; index < 4; index++) {
  12240. var offsetLocation = offsetLocations[index];
  12241. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12242. this._gl.enableVertexAttribArray(offsetLocation);
  12243. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12244. }
  12245. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12246. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12247. this._currentInstanceLocations.push(offsetLocation);
  12248. this._currentInstanceBuffers.push(instancesBuffer);
  12249. }
  12250. }
  12251. };
  12252. Engine.prototype.applyStates = function () {
  12253. this._depthCullingState.apply(this._gl);
  12254. this._stencilState.apply(this._gl);
  12255. this._alphaState.apply(this._gl);
  12256. };
  12257. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12258. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12259. };
  12260. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12261. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12262. };
  12263. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12264. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12265. };
  12266. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12267. // Apply states
  12268. this.applyStates();
  12269. this._drawCalls.addCount(1, false);
  12270. // Render
  12271. var drawMode = this.DrawMode(fillMode);
  12272. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12273. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12274. if (instancesCount) {
  12275. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12276. }
  12277. else {
  12278. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12279. }
  12280. };
  12281. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12282. // Apply states
  12283. this.applyStates();
  12284. this._drawCalls.addCount(1, false);
  12285. var drawMode = this.DrawMode(fillMode);
  12286. if (instancesCount) {
  12287. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12288. }
  12289. else {
  12290. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12291. }
  12292. };
  12293. Engine.prototype.DrawMode = function (fillMode) {
  12294. switch (fillMode) {
  12295. // Triangle views
  12296. case BABYLON.Material.TriangleFillMode:
  12297. return this._gl.TRIANGLES;
  12298. case BABYLON.Material.PointFillMode:
  12299. return this._gl.POINTS;
  12300. case BABYLON.Material.WireFrameFillMode:
  12301. return this._gl.LINES;
  12302. // Draw modes
  12303. case BABYLON.Material.PointListDrawMode:
  12304. return this._gl.POINTS;
  12305. case BABYLON.Material.LineListDrawMode:
  12306. return this._gl.LINES;
  12307. case BABYLON.Material.LineLoopDrawMode:
  12308. return this._gl.LINE_LOOP;
  12309. case BABYLON.Material.LineStripDrawMode:
  12310. return this._gl.LINE_STRIP;
  12311. case BABYLON.Material.TriangleStripDrawMode:
  12312. return this._gl.TRIANGLE_STRIP;
  12313. case BABYLON.Material.TriangleFanDrawMode:
  12314. return this._gl.TRIANGLE_FAN;
  12315. default:
  12316. return this._gl.TRIANGLES;
  12317. }
  12318. };
  12319. // Shaders
  12320. Engine.prototype._releaseEffect = function (effect) {
  12321. if (this._compiledEffects[effect._key]) {
  12322. delete this._compiledEffects[effect._key];
  12323. this._deleteProgram(effect.getProgram());
  12324. }
  12325. };
  12326. Engine.prototype._deleteProgram = function (program) {
  12327. if (program) {
  12328. program.__SPECTOR_rebuildProgram = null;
  12329. if (program.transformFeedback) {
  12330. this.deleteTransformFeedback(program.transformFeedback);
  12331. program.transformFeedback = null;
  12332. }
  12333. this._gl.deleteProgram(program);
  12334. }
  12335. };
  12336. /**
  12337. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12338. * @param samplers An array of string used to represent textures
  12339. */
  12340. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12341. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12342. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12343. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12344. if (this._compiledEffects[name]) {
  12345. var compiledEffect = this._compiledEffects[name];
  12346. if (onCompiled && compiledEffect.isReady()) {
  12347. onCompiled(compiledEffect);
  12348. }
  12349. return compiledEffect;
  12350. }
  12351. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12352. effect._key = name;
  12353. this._compiledEffects[name] = effect;
  12354. return effect;
  12355. };
  12356. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12357. if (uniformsNames === void 0) { uniformsNames = []; }
  12358. if (samplers === void 0) { samplers = []; }
  12359. if (defines === void 0) { defines = ""; }
  12360. return this.createEffect({
  12361. vertex: "particles",
  12362. fragmentElement: fragmentName
  12363. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12364. };
  12365. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12366. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12367. context = context || this._gl;
  12368. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12369. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12370. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12371. };
  12372. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12373. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12374. context = context || this._gl;
  12375. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12376. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12377. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12378. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12379. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12380. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12381. return program;
  12382. };
  12383. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12384. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12385. var shaderProgram = context.createProgram();
  12386. if (!shaderProgram) {
  12387. throw new Error("Unable to create program");
  12388. }
  12389. context.attachShader(shaderProgram, vertexShader);
  12390. context.attachShader(shaderProgram, fragmentShader);
  12391. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12392. var transformFeedback = this.createTransformFeedback();
  12393. this.bindTransformFeedback(transformFeedback);
  12394. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12395. shaderProgram.transformFeedback = transformFeedback;
  12396. }
  12397. context.linkProgram(shaderProgram);
  12398. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12399. this.bindTransformFeedback(null);
  12400. }
  12401. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12402. if (!linked) {
  12403. context.validateProgram(shaderProgram);
  12404. var error = context.getProgramInfoLog(shaderProgram);
  12405. if (error) {
  12406. throw new Error(error);
  12407. }
  12408. }
  12409. context.deleteShader(vertexShader);
  12410. context.deleteShader(fragmentShader);
  12411. return shaderProgram;
  12412. };
  12413. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12414. var results = new Array();
  12415. for (var index = 0; index < uniformsNames.length; index++) {
  12416. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12417. }
  12418. return results;
  12419. };
  12420. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12421. var results = [];
  12422. for (var index = 0; index < attributesNames.length; index++) {
  12423. try {
  12424. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12425. }
  12426. catch (e) {
  12427. results.push(-1);
  12428. }
  12429. }
  12430. return results;
  12431. };
  12432. Engine.prototype.enableEffect = function (effect) {
  12433. if (!effect) {
  12434. return;
  12435. }
  12436. // Use program
  12437. this.bindSamplers(effect);
  12438. this._currentEffect = effect;
  12439. if (effect.onBind) {
  12440. effect.onBind(effect);
  12441. }
  12442. effect.onBindObservable.notifyObservers(effect);
  12443. };
  12444. Engine.prototype.setIntArray = function (uniform, array) {
  12445. if (!uniform)
  12446. return;
  12447. this._gl.uniform1iv(uniform, array);
  12448. };
  12449. Engine.prototype.setIntArray2 = function (uniform, array) {
  12450. if (!uniform || array.length % 2 !== 0)
  12451. return;
  12452. this._gl.uniform2iv(uniform, array);
  12453. };
  12454. Engine.prototype.setIntArray3 = function (uniform, array) {
  12455. if (!uniform || array.length % 3 !== 0)
  12456. return;
  12457. this._gl.uniform3iv(uniform, array);
  12458. };
  12459. Engine.prototype.setIntArray4 = function (uniform, array) {
  12460. if (!uniform || array.length % 4 !== 0)
  12461. return;
  12462. this._gl.uniform4iv(uniform, array);
  12463. };
  12464. Engine.prototype.setFloatArray = function (uniform, array) {
  12465. if (!uniform)
  12466. return;
  12467. this._gl.uniform1fv(uniform, array);
  12468. };
  12469. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12470. if (!uniform || array.length % 2 !== 0)
  12471. return;
  12472. this._gl.uniform2fv(uniform, array);
  12473. };
  12474. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12475. if (!uniform || array.length % 3 !== 0)
  12476. return;
  12477. this._gl.uniform3fv(uniform, array);
  12478. };
  12479. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12480. if (!uniform || array.length % 4 !== 0)
  12481. return;
  12482. this._gl.uniform4fv(uniform, array);
  12483. };
  12484. Engine.prototype.setArray = function (uniform, array) {
  12485. if (!uniform)
  12486. return;
  12487. this._gl.uniform1fv(uniform, array);
  12488. };
  12489. Engine.prototype.setArray2 = function (uniform, array) {
  12490. if (!uniform || array.length % 2 !== 0)
  12491. return;
  12492. this._gl.uniform2fv(uniform, array);
  12493. };
  12494. Engine.prototype.setArray3 = function (uniform, array) {
  12495. if (!uniform || array.length % 3 !== 0)
  12496. return;
  12497. this._gl.uniform3fv(uniform, array);
  12498. };
  12499. Engine.prototype.setArray4 = function (uniform, array) {
  12500. if (!uniform || array.length % 4 !== 0)
  12501. return;
  12502. this._gl.uniform4fv(uniform, array);
  12503. };
  12504. Engine.prototype.setMatrices = function (uniform, matrices) {
  12505. if (!uniform)
  12506. return;
  12507. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12508. };
  12509. Engine.prototype.setMatrix = function (uniform, matrix) {
  12510. if (!uniform)
  12511. return;
  12512. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12513. };
  12514. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12515. if (!uniform)
  12516. return;
  12517. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12518. };
  12519. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12520. if (!uniform)
  12521. return;
  12522. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12523. };
  12524. Engine.prototype.setInt = function (uniform, value) {
  12525. if (!uniform)
  12526. return;
  12527. this._gl.uniform1i(uniform, value);
  12528. };
  12529. Engine.prototype.setFloat = function (uniform, value) {
  12530. if (!uniform)
  12531. return;
  12532. this._gl.uniform1f(uniform, value);
  12533. };
  12534. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12535. if (!uniform)
  12536. return;
  12537. this._gl.uniform2f(uniform, x, y);
  12538. };
  12539. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12540. if (!uniform)
  12541. return;
  12542. this._gl.uniform3f(uniform, x, y, z);
  12543. };
  12544. Engine.prototype.setBool = function (uniform, bool) {
  12545. if (!uniform)
  12546. return;
  12547. this._gl.uniform1i(uniform, bool);
  12548. };
  12549. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12550. if (!uniform)
  12551. return;
  12552. this._gl.uniform4f(uniform, x, y, z, w);
  12553. };
  12554. Engine.prototype.setColor3 = function (uniform, color3) {
  12555. if (!uniform)
  12556. return;
  12557. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12558. };
  12559. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12560. if (!uniform)
  12561. return;
  12562. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12563. };
  12564. /**
  12565. * Sets a Color4 on a uniform variable
  12566. * @param uniform defines the uniform location
  12567. * @param color4 defines the value to be set
  12568. */
  12569. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12570. if (!uniform)
  12571. return;
  12572. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12573. };
  12574. // States
  12575. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12576. if (zOffset === void 0) { zOffset = 0; }
  12577. if (reverseSide === void 0) { reverseSide = false; }
  12578. // Culling
  12579. if (this._depthCullingState.cull !== culling || force) {
  12580. this._depthCullingState.cull = culling;
  12581. }
  12582. // Cull face
  12583. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12584. if (this._depthCullingState.cullFace !== cullFace || force) {
  12585. this._depthCullingState.cullFace = cullFace;
  12586. }
  12587. // Z offset
  12588. this.setZOffset(zOffset);
  12589. // Front face
  12590. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12591. if (this._depthCullingState.frontFace !== frontFace || force) {
  12592. this._depthCullingState.frontFace = frontFace;
  12593. }
  12594. };
  12595. Engine.prototype.setZOffset = function (value) {
  12596. this._depthCullingState.zOffset = value;
  12597. };
  12598. Engine.prototype.getZOffset = function () {
  12599. return this._depthCullingState.zOffset;
  12600. };
  12601. Engine.prototype.setDepthBuffer = function (enable) {
  12602. this._depthCullingState.depthTest = enable;
  12603. };
  12604. Engine.prototype.getDepthWrite = function () {
  12605. return this._depthCullingState.depthMask;
  12606. };
  12607. Engine.prototype.setDepthWrite = function (enable) {
  12608. this._depthCullingState.depthMask = enable;
  12609. };
  12610. Engine.prototype.setColorWrite = function (enable) {
  12611. this._gl.colorMask(enable, enable, enable, enable);
  12612. this._colorWrite = enable;
  12613. };
  12614. Engine.prototype.getColorWrite = function () {
  12615. return this._colorWrite;
  12616. };
  12617. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12618. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12619. };
  12620. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12621. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12622. if (this._alphaMode === mode) {
  12623. return;
  12624. }
  12625. switch (mode) {
  12626. case Engine.ALPHA_DISABLE:
  12627. this._alphaState.alphaBlend = false;
  12628. break;
  12629. case Engine.ALPHA_PREMULTIPLIED:
  12630. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12631. this._alphaState.alphaBlend = true;
  12632. break;
  12633. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12634. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12635. this._alphaState.alphaBlend = true;
  12636. break;
  12637. case Engine.ALPHA_COMBINE:
  12638. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12639. this._alphaState.alphaBlend = true;
  12640. break;
  12641. case Engine.ALPHA_ONEONE:
  12642. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12643. this._alphaState.alphaBlend = true;
  12644. break;
  12645. case Engine.ALPHA_ADD:
  12646. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12647. this._alphaState.alphaBlend = true;
  12648. break;
  12649. case Engine.ALPHA_SUBTRACT:
  12650. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12651. this._alphaState.alphaBlend = true;
  12652. break;
  12653. case Engine.ALPHA_MULTIPLY:
  12654. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12655. this._alphaState.alphaBlend = true;
  12656. break;
  12657. case Engine.ALPHA_MAXIMIZED:
  12658. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12659. this._alphaState.alphaBlend = true;
  12660. break;
  12661. case Engine.ALPHA_INTERPOLATE:
  12662. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12663. this._alphaState.alphaBlend = true;
  12664. break;
  12665. case Engine.ALPHA_SCREENMODE:
  12666. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12667. this._alphaState.alphaBlend = true;
  12668. break;
  12669. }
  12670. if (!noDepthWriteChange) {
  12671. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12672. }
  12673. this._alphaMode = mode;
  12674. };
  12675. Engine.prototype.getAlphaMode = function () {
  12676. return this._alphaMode;
  12677. };
  12678. // Textures
  12679. Engine.prototype.wipeCaches = function (bruteForce) {
  12680. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12681. return;
  12682. }
  12683. this._currentEffect = null;
  12684. // 6/8/2017: deltakosh: Should not be required anymore.
  12685. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12686. if (bruteForce) {
  12687. this.resetTextureCache();
  12688. this._currentProgram = null;
  12689. this._stencilState.reset();
  12690. this._depthCullingState.reset();
  12691. this.setDepthFunctionToLessOrEqual();
  12692. this._alphaState.reset();
  12693. }
  12694. this._resetVertexBufferBinding();
  12695. this._cachedIndexBuffer = null;
  12696. this._cachedEffectForVertexBuffers = null;
  12697. this._unbindVertexArrayObject();
  12698. this.bindIndexBuffer(null);
  12699. };
  12700. /**
  12701. * Set the compressed texture format to use, based on the formats you have, and the formats
  12702. * supported by the hardware / browser.
  12703. *
  12704. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12705. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12706. * to API arguments needed to compressed textures. This puts the burden on the container
  12707. * generator to house the arcane code for determining these for current & future formats.
  12708. *
  12709. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12710. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12711. *
  12712. * Note: The result of this call is not taken into account when a texture is base64.
  12713. *
  12714. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12715. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12716. *
  12717. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12718. * @returns The extension selected.
  12719. */
  12720. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12721. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12722. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12723. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12724. return this._textureFormatInUse = this._texturesSupported[i];
  12725. }
  12726. }
  12727. }
  12728. // actively set format to nothing, to allow this to be called more than once
  12729. // and possibly fail the 2nd time
  12730. this._textureFormatInUse = null;
  12731. return null;
  12732. };
  12733. Engine.prototype._createTexture = function () {
  12734. var texture = this._gl.createTexture();
  12735. if (!texture) {
  12736. throw new Error("Unable to create texture");
  12737. }
  12738. return texture;
  12739. };
  12740. /**
  12741. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12742. * @param {string} urlArg- This contains one of the following:
  12743. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12744. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12745. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12746. *
  12747. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12748. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12749. * @param {Scene} scene- Needed for loading to the correct scene.
  12750. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12751. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12752. * @param {callback} onError- Optional callback to be called upon failure.
  12753. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12754. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12755. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12756. *
  12757. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12758. */
  12759. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12760. var _this = this;
  12761. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12762. if (onLoad === void 0) { onLoad = null; }
  12763. if (onError === void 0) { onError = null; }
  12764. if (buffer === void 0) { buffer = null; }
  12765. if (fallBack === void 0) { fallBack = null; }
  12766. if (format === void 0) { format = null; }
  12767. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12768. var fromData = url.substr(0, 5) === "data:";
  12769. var fromBlob = url.substr(0, 5) === "blob:";
  12770. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12771. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12772. // establish the file extension, if possible
  12773. var lastDot = url.lastIndexOf('.');
  12774. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12775. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12776. var isTGA = (extension.indexOf(".tga") === 0);
  12777. // determine if a ktx file should be substituted
  12778. var isKTX = false;
  12779. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12780. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12781. isKTX = true;
  12782. }
  12783. if (scene) {
  12784. scene._addPendingData(texture);
  12785. }
  12786. texture.url = url;
  12787. texture.generateMipMaps = !noMipmap;
  12788. texture.samplingMode = samplingMode;
  12789. texture.invertY = invertY;
  12790. if (!this._doNotHandleContextLost) {
  12791. // Keep a link to the buffer only if we plan to handle context lost
  12792. texture._buffer = buffer;
  12793. }
  12794. var onLoadObserver = null;
  12795. if (onLoad && !fallBack) {
  12796. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12797. }
  12798. if (!fallBack)
  12799. this._internalTexturesCache.push(texture);
  12800. var onerror = function (message, exception) {
  12801. if (scene) {
  12802. scene._removePendingData(texture);
  12803. }
  12804. if (onLoadObserver) {
  12805. texture.onLoadedObservable.remove(onLoadObserver);
  12806. }
  12807. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12808. if (isKTX) {
  12809. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12810. }
  12811. else if (BABYLON.Tools.UseFallbackTexture) {
  12812. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12813. }
  12814. if (onError) {
  12815. onError(message || "Unknown error", exception);
  12816. }
  12817. };
  12818. var callback = null;
  12819. // processing for non-image formats
  12820. if (isKTX || isTGA || isDDS) {
  12821. if (isKTX) {
  12822. callback = function (data) {
  12823. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12824. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12825. ktx.uploadLevels(_this._gl, !noMipmap);
  12826. return false;
  12827. }, samplingMode);
  12828. };
  12829. }
  12830. else if (isTGA) {
  12831. callback = function (arrayBuffer) {
  12832. var data = new Uint8Array(arrayBuffer);
  12833. var header = BABYLON.TGATools.GetTGAHeader(data);
  12834. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12835. BABYLON.TGATools.UploadContent(_this._gl, data);
  12836. return false;
  12837. }, samplingMode);
  12838. };
  12839. }
  12840. else if (isDDS) {
  12841. callback = function (data) {
  12842. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12843. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12844. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12845. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12846. return false;
  12847. }, samplingMode);
  12848. };
  12849. }
  12850. if (!buffer) {
  12851. this._loadFile(url, function (data) {
  12852. if (callback) {
  12853. callback(data);
  12854. }
  12855. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12856. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12857. });
  12858. }
  12859. else {
  12860. if (callback) {
  12861. callback(buffer);
  12862. }
  12863. }
  12864. // image format processing
  12865. }
  12866. else {
  12867. var onload = function (img) {
  12868. if (fromBlob && !_this._doNotHandleContextLost) {
  12869. // We need to store the image if we need to rebuild the texture
  12870. // in case of a webgl context lost
  12871. texture._buffer = img;
  12872. }
  12873. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12874. var gl = _this._gl;
  12875. var isPot = (img.width === potWidth && img.height === potHeight);
  12876. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12877. if (isPot) {
  12878. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12879. return false;
  12880. }
  12881. // Using shaders to rescale because canvas.drawImage is lossy
  12882. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12883. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12884. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12885. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12886. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12887. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12888. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12889. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12890. _this._releaseTexture(source);
  12891. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12892. continuationCallback();
  12893. });
  12894. return true;
  12895. }, samplingMode);
  12896. };
  12897. if (!fromData || isBase64)
  12898. if (buffer instanceof HTMLImageElement) {
  12899. onload(buffer);
  12900. }
  12901. else {
  12902. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12903. }
  12904. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12905. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12906. else
  12907. onload(buffer);
  12908. }
  12909. return texture;
  12910. };
  12911. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12912. var _this = this;
  12913. var rtt = this.createRenderTargetTexture({
  12914. width: destination.width,
  12915. height: destination.height,
  12916. }, {
  12917. generateMipMaps: false,
  12918. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12919. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12920. generateDepthBuffer: false,
  12921. generateStencilBuffer: false
  12922. });
  12923. if (!this._rescalePostProcess) {
  12924. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12925. }
  12926. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12927. _this._rescalePostProcess.onApply = function (effect) {
  12928. effect._bindTexture("textureSampler", source);
  12929. };
  12930. var hostingScene = scene;
  12931. if (!hostingScene) {
  12932. hostingScene = _this.scenes[_this.scenes.length - 1];
  12933. }
  12934. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12935. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12936. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12937. _this.unBindFramebuffer(rtt);
  12938. _this._releaseTexture(rtt);
  12939. if (onComplete) {
  12940. onComplete();
  12941. }
  12942. });
  12943. };
  12944. Engine.prototype._getInternalFormat = function (format) {
  12945. var internalFormat = this._gl.RGBA;
  12946. switch (format) {
  12947. case Engine.TEXTUREFORMAT_ALPHA:
  12948. internalFormat = this._gl.ALPHA;
  12949. break;
  12950. case Engine.TEXTUREFORMAT_LUMINANCE:
  12951. internalFormat = this._gl.LUMINANCE;
  12952. break;
  12953. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12954. internalFormat = this._gl.LUMINANCE_ALPHA;
  12955. break;
  12956. case Engine.TEXTUREFORMAT_RGB:
  12957. case Engine.TEXTUREFORMAT_RGB32F:
  12958. internalFormat = this._gl.RGB;
  12959. break;
  12960. case Engine.TEXTUREFORMAT_RGBA:
  12961. case Engine.TEXTUREFORMAT_RGBA32F:
  12962. internalFormat = this._gl.RGBA;
  12963. break;
  12964. case Engine.TEXTUREFORMAT_R32F:
  12965. internalFormat = this._gl.RED;
  12966. break;
  12967. case Engine.TEXTUREFORMAT_RG32F:
  12968. internalFormat = this._gl.RG;
  12969. break;
  12970. }
  12971. return internalFormat;
  12972. };
  12973. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12974. if (compression === void 0) { compression = null; }
  12975. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12976. if (!texture) {
  12977. return;
  12978. }
  12979. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  12980. var internalFormat = this._getInternalFormat(format);
  12981. var textureType = this._getWebGLTextureType(type);
  12982. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12983. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12984. if (!this._doNotHandleContextLost) {
  12985. texture._bufferView = data;
  12986. texture.format = format;
  12987. texture.type = type;
  12988. texture.invertY = invertY;
  12989. texture._compression = compression;
  12990. }
  12991. if (texture.width % 4 !== 0) {
  12992. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12993. }
  12994. if (compression && data) {
  12995. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12996. }
  12997. else {
  12998. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12999. }
  13000. if (texture.generateMipMaps) {
  13001. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13002. }
  13003. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13004. // this.resetTextureCache();
  13005. texture.isReady = true;
  13006. };
  13007. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13008. if (compression === void 0) { compression = null; }
  13009. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13010. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13011. texture.baseWidth = width;
  13012. texture.baseHeight = height;
  13013. texture.width = width;
  13014. texture.height = height;
  13015. texture.format = format;
  13016. texture.generateMipMaps = generateMipMaps;
  13017. texture.samplingMode = samplingMode;
  13018. texture.invertY = invertY;
  13019. texture._compression = compression;
  13020. texture.type = type;
  13021. if (!this._doNotHandleContextLost) {
  13022. texture._bufferView = data;
  13023. }
  13024. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13025. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13026. // Filters
  13027. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13028. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13029. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13030. if (generateMipMaps) {
  13031. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13032. }
  13033. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13034. this._internalTexturesCache.push(texture);
  13035. return texture;
  13036. };
  13037. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13038. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13039. texture.baseWidth = width;
  13040. texture.baseHeight = height;
  13041. if (generateMipMaps) {
  13042. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13043. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13044. }
  13045. // this.resetTextureCache();
  13046. texture.width = width;
  13047. texture.height = height;
  13048. texture.isReady = false;
  13049. texture.generateMipMaps = generateMipMaps;
  13050. texture.samplingMode = samplingMode;
  13051. this.updateTextureSamplingMode(samplingMode, texture);
  13052. this._internalTexturesCache.push(texture);
  13053. return texture;
  13054. };
  13055. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13056. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13057. if (texture.isCube) {
  13058. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13059. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13060. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13061. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13062. }
  13063. else if (texture.is3D) {
  13064. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13065. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13066. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13067. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13068. }
  13069. else {
  13070. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13071. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13072. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13073. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13074. }
  13075. texture.samplingMode = samplingMode;
  13076. };
  13077. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13078. if (premulAlpha === void 0) { premulAlpha = false; }
  13079. if (!texture) {
  13080. return;
  13081. }
  13082. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13083. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13084. if (premulAlpha) {
  13085. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13086. }
  13087. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13088. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13089. if (texture.generateMipMaps) {
  13090. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13091. }
  13092. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13093. if (premulAlpha) {
  13094. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13095. }
  13096. texture.isReady = true;
  13097. };
  13098. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13099. if (!texture || texture._isDisabled) {
  13100. return;
  13101. }
  13102. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13103. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13104. try {
  13105. // Testing video texture support
  13106. if (this._videoTextureSupported === undefined) {
  13107. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13108. if (this._gl.getError() !== 0) {
  13109. this._videoTextureSupported = false;
  13110. }
  13111. else {
  13112. this._videoTextureSupported = true;
  13113. }
  13114. }
  13115. // Copy video through the current working canvas if video texture is not supported
  13116. if (!this._videoTextureSupported) {
  13117. if (!texture._workingCanvas) {
  13118. texture._workingCanvas = document.createElement("canvas");
  13119. var context = texture._workingCanvas.getContext("2d");
  13120. if (!context) {
  13121. throw new Error("Unable to get 2d context");
  13122. }
  13123. texture._workingContext = context;
  13124. texture._workingCanvas.width = texture.width;
  13125. texture._workingCanvas.height = texture.height;
  13126. }
  13127. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13128. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13129. }
  13130. else {
  13131. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13132. }
  13133. if (texture.generateMipMaps) {
  13134. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13135. }
  13136. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13137. // this.resetTextureCache();
  13138. texture.isReady = true;
  13139. }
  13140. catch (ex) {
  13141. // Something unexpected
  13142. // Let's disable the texture
  13143. texture._isDisabled = true;
  13144. }
  13145. };
  13146. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13147. var fullOptions = new RenderTargetCreationOptions();
  13148. if (options !== undefined && typeof options === "object") {
  13149. fullOptions.generateMipMaps = options.generateMipMaps;
  13150. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13151. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13152. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13153. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13154. }
  13155. else {
  13156. fullOptions.generateMipMaps = options;
  13157. fullOptions.generateDepthBuffer = true;
  13158. fullOptions.generateStencilBuffer = false;
  13159. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13160. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13161. }
  13162. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13163. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13164. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13165. }
  13166. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13167. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13168. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13169. }
  13170. var gl = this._gl;
  13171. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13172. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13173. var width = size.width || size;
  13174. var height = size.height || size;
  13175. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13176. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13177. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13178. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13179. }
  13180. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13181. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13182. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13183. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13184. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13185. // Create the framebuffer
  13186. var framebuffer = gl.createFramebuffer();
  13187. this.bindUnboundFramebuffer(framebuffer);
  13188. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13189. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13190. if (fullOptions.generateMipMaps) {
  13191. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13192. }
  13193. // Unbind
  13194. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13195. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13196. this.bindUnboundFramebuffer(null);
  13197. texture._framebuffer = framebuffer;
  13198. texture.baseWidth = width;
  13199. texture.baseHeight = height;
  13200. texture.width = width;
  13201. texture.height = height;
  13202. texture.isReady = true;
  13203. texture.samples = 1;
  13204. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13205. texture.samplingMode = fullOptions.samplingMode;
  13206. texture.type = fullOptions.type;
  13207. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13208. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13209. // this.resetTextureCache();
  13210. this._internalTexturesCache.push(texture);
  13211. return texture;
  13212. };
  13213. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13214. var generateMipMaps = false;
  13215. var generateDepthBuffer = true;
  13216. var generateStencilBuffer = false;
  13217. var generateDepthTexture = false;
  13218. var textureCount = 1;
  13219. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13220. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13221. var types = [], samplingModes = [];
  13222. if (options !== undefined) {
  13223. generateMipMaps = options.generateMipMaps;
  13224. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13225. generateStencilBuffer = options.generateStencilBuffer;
  13226. generateDepthTexture = options.generateDepthTexture;
  13227. textureCount = options.textureCount || 1;
  13228. if (options.types) {
  13229. types = options.types;
  13230. }
  13231. if (options.samplingModes) {
  13232. samplingModes = options.samplingModes;
  13233. }
  13234. }
  13235. var gl = this._gl;
  13236. // Create the framebuffer
  13237. var framebuffer = gl.createFramebuffer();
  13238. this.bindUnboundFramebuffer(framebuffer);
  13239. var width = size.width || size;
  13240. var height = size.height || size;
  13241. var textures = [];
  13242. var attachments = [];
  13243. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13244. for (var i = 0; i < textureCount; i++) {
  13245. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13246. var type = types[i] || defaultType;
  13247. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13248. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13249. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13250. }
  13251. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13252. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13253. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13254. }
  13255. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13256. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13257. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13258. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13259. }
  13260. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13261. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13262. textures.push(texture);
  13263. attachments.push(attachment);
  13264. gl.activeTexture(gl["TEXTURE" + i]);
  13265. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13267. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13270. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13271. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13272. if (generateMipMaps) {
  13273. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13274. }
  13275. // Unbind
  13276. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13277. texture._framebuffer = framebuffer;
  13278. texture._depthStencilBuffer = depthStencilBuffer;
  13279. texture.baseWidth = width;
  13280. texture.baseHeight = height;
  13281. texture.width = width;
  13282. texture.height = height;
  13283. texture.isReady = true;
  13284. texture.samples = 1;
  13285. texture.generateMipMaps = generateMipMaps;
  13286. texture.samplingMode = samplingMode;
  13287. texture.type = type;
  13288. texture._generateDepthBuffer = generateDepthBuffer;
  13289. texture._generateStencilBuffer = generateStencilBuffer;
  13290. texture._attachments = attachments;
  13291. this._internalTexturesCache.push(texture);
  13292. }
  13293. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13294. // Depth texture
  13295. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13296. gl.activeTexture(gl.TEXTURE0);
  13297. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13298. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13300. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13301. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13302. 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);
  13303. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13304. depthTexture._framebuffer = framebuffer;
  13305. depthTexture.baseWidth = width;
  13306. depthTexture.baseHeight = height;
  13307. depthTexture.width = width;
  13308. depthTexture.height = height;
  13309. depthTexture.isReady = true;
  13310. depthTexture.samples = 1;
  13311. depthTexture.generateMipMaps = generateMipMaps;
  13312. depthTexture.samplingMode = gl.NEAREST;
  13313. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13314. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13315. textures.push(depthTexture);
  13316. this._internalTexturesCache.push(depthTexture);
  13317. }
  13318. gl.drawBuffers(attachments);
  13319. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13320. this.bindUnboundFramebuffer(null);
  13321. this.resetTextureCache();
  13322. return textures;
  13323. };
  13324. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13325. if (samples === void 0) { samples = 1; }
  13326. var depthStencilBuffer = null;
  13327. var gl = this._gl;
  13328. // Create the depth/stencil buffer
  13329. if (generateStencilBuffer) {
  13330. depthStencilBuffer = gl.createRenderbuffer();
  13331. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13332. if (samples > 1) {
  13333. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13334. }
  13335. else {
  13336. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13337. }
  13338. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13339. }
  13340. else if (generateDepthBuffer) {
  13341. depthStencilBuffer = gl.createRenderbuffer();
  13342. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13343. if (samples > 1) {
  13344. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13345. }
  13346. else {
  13347. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13348. }
  13349. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13350. }
  13351. return depthStencilBuffer;
  13352. };
  13353. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13354. if (this.webGLVersion < 2 || !texture) {
  13355. return 1;
  13356. }
  13357. if (texture.samples === samples) {
  13358. return samples;
  13359. }
  13360. var gl = this._gl;
  13361. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13362. // Dispose previous render buffers
  13363. if (texture._depthStencilBuffer) {
  13364. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13365. texture._depthStencilBuffer = null;
  13366. }
  13367. if (texture._MSAAFramebuffer) {
  13368. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13369. texture._MSAAFramebuffer = null;
  13370. }
  13371. if (texture._MSAARenderBuffer) {
  13372. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13373. texture._MSAARenderBuffer = null;
  13374. }
  13375. if (samples > 1) {
  13376. var framebuffer = gl.createFramebuffer();
  13377. if (!framebuffer) {
  13378. throw new Error("Unable to create multi sampled framebuffer");
  13379. }
  13380. texture._MSAAFramebuffer = framebuffer;
  13381. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13382. var colorRenderbuffer = gl.createRenderbuffer();
  13383. if (!colorRenderbuffer) {
  13384. throw new Error("Unable to create multi sampled framebuffer");
  13385. }
  13386. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13387. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13388. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13389. texture._MSAARenderBuffer = colorRenderbuffer;
  13390. }
  13391. else {
  13392. this.bindUnboundFramebuffer(texture._framebuffer);
  13393. }
  13394. texture.samples = samples;
  13395. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13396. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13397. this.bindUnboundFramebuffer(null);
  13398. return samples;
  13399. };
  13400. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13401. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13402. return 1;
  13403. }
  13404. if (textures[0].samples === samples) {
  13405. return samples;
  13406. }
  13407. var gl = this._gl;
  13408. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13409. // Dispose previous render buffers
  13410. if (textures[0]._depthStencilBuffer) {
  13411. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13412. textures[0]._depthStencilBuffer = null;
  13413. }
  13414. if (textures[0]._MSAAFramebuffer) {
  13415. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13416. textures[0]._MSAAFramebuffer = null;
  13417. }
  13418. for (var i = 0; i < textures.length; i++) {
  13419. if (textures[i]._MSAARenderBuffer) {
  13420. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13421. textures[i]._MSAARenderBuffer = null;
  13422. }
  13423. }
  13424. if (samples > 1) {
  13425. var framebuffer = gl.createFramebuffer();
  13426. if (!framebuffer) {
  13427. throw new Error("Unable to create multi sampled framebuffer");
  13428. }
  13429. this.bindUnboundFramebuffer(framebuffer);
  13430. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13431. var attachments = [];
  13432. for (var i = 0; i < textures.length; i++) {
  13433. var texture = textures[i];
  13434. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13435. var colorRenderbuffer = gl.createRenderbuffer();
  13436. if (!colorRenderbuffer) {
  13437. throw new Error("Unable to create multi sampled framebuffer");
  13438. }
  13439. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13440. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13441. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13442. texture._MSAAFramebuffer = framebuffer;
  13443. texture._MSAARenderBuffer = colorRenderbuffer;
  13444. texture.samples = samples;
  13445. texture._depthStencilBuffer = depthStencilBuffer;
  13446. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13447. attachments.push(attachment);
  13448. }
  13449. gl.drawBuffers(attachments);
  13450. }
  13451. else {
  13452. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13453. }
  13454. this.bindUnboundFramebuffer(null);
  13455. return samples;
  13456. };
  13457. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13458. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13459. };
  13460. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13461. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13462. };
  13463. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13464. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13465. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13466. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13467. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13468. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13469. }
  13470. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13471. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13472. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13473. }
  13474. var gl = this._gl;
  13475. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13476. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13477. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13478. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13479. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13480. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13481. }
  13482. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13483. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13484. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13485. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13486. for (var face = 0; face < 6; face++) {
  13487. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13488. }
  13489. // Create the framebuffer
  13490. var framebuffer = gl.createFramebuffer();
  13491. this.bindUnboundFramebuffer(framebuffer);
  13492. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13493. // MipMaps
  13494. if (fullOptions.generateMipMaps) {
  13495. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13496. }
  13497. // Unbind
  13498. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13499. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13500. this.bindUnboundFramebuffer(null);
  13501. texture._framebuffer = framebuffer;
  13502. texture.width = size;
  13503. texture.height = size;
  13504. texture.isReady = true;
  13505. texture.isCube = true;
  13506. texture.samples = 1;
  13507. texture.generateMipMaps = fullOptions.generateMipMaps;
  13508. texture.samplingMode = fullOptions.samplingMode;
  13509. texture.type = fullOptions.type;
  13510. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13511. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13512. this._internalTexturesCache.push(texture);
  13513. return texture;
  13514. };
  13515. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13516. var _this = this;
  13517. if (onLoad === void 0) { onLoad = null; }
  13518. if (onError === void 0) { onError = null; }
  13519. if (forcedExtension === void 0) { forcedExtension = null; }
  13520. var callback = function (loadData) {
  13521. if (!loadData) {
  13522. if (onLoad) {
  13523. onLoad(null);
  13524. }
  13525. return;
  13526. }
  13527. var texture = loadData.texture;
  13528. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13529. texture._lodGenerationScale = scale;
  13530. texture._lodGenerationOffset = offset;
  13531. if (_this._caps.textureLOD) {
  13532. // Do not add extra process if texture lod is supported.
  13533. if (onLoad) {
  13534. onLoad(texture);
  13535. }
  13536. return;
  13537. }
  13538. var mipSlices = 3;
  13539. var gl = _this._gl;
  13540. var width = loadData.width;
  13541. if (!width) {
  13542. return;
  13543. }
  13544. var textures = [];
  13545. for (var i = 0; i < mipSlices; i++) {
  13546. //compute LOD from even spacing in smoothness (matching shader calculation)
  13547. var smoothness = i / (mipSlices - 1);
  13548. var roughness = 1 - smoothness;
  13549. var minLODIndex = offset; // roughness = 0
  13550. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13551. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13552. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13553. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13554. glTextureFromLod.isCube = true;
  13555. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13556. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13557. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13558. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13559. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13560. if (loadData.isDDS) {
  13561. var info = loadData.info;
  13562. var data = loadData.data;
  13563. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13564. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13565. }
  13566. else {
  13567. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13568. }
  13569. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13570. // Wrap in a base texture for easy binding.
  13571. var lodTexture = new BABYLON.BaseTexture(scene);
  13572. lodTexture.isCube = true;
  13573. lodTexture._texture = glTextureFromLod;
  13574. glTextureFromLod.isReady = true;
  13575. textures.push(lodTexture);
  13576. }
  13577. texture._lodTextureHigh = textures[2];
  13578. texture._lodTextureMid = textures[1];
  13579. texture._lodTextureLow = textures[0];
  13580. if (onLoad) {
  13581. onLoad(texture);
  13582. }
  13583. };
  13584. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13585. };
  13586. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13587. var _this = this;
  13588. if (onLoad === void 0) { onLoad = null; }
  13589. if (onError === void 0) { onError = null; }
  13590. if (forcedExtension === void 0) { forcedExtension = null; }
  13591. var gl = this._gl;
  13592. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13593. texture.isCube = true;
  13594. texture.url = rootUrl;
  13595. texture.generateMipMaps = !noMipmap;
  13596. if (!this._doNotHandleContextLost) {
  13597. texture._extension = forcedExtension;
  13598. texture._files = files;
  13599. }
  13600. var isKTX = false;
  13601. var isDDS = false;
  13602. var lastDot = rootUrl.lastIndexOf('.');
  13603. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13604. if (this._textureFormatInUse) {
  13605. extension = this._textureFormatInUse;
  13606. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13607. isKTX = true;
  13608. }
  13609. else {
  13610. isDDS = (extension === ".dds");
  13611. }
  13612. var onerror = function (request, exception) {
  13613. if (onError && request) {
  13614. onError(request.status + " " + request.statusText, exception);
  13615. }
  13616. };
  13617. if (isKTX) {
  13618. this._loadFile(rootUrl, function (data) {
  13619. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13620. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13621. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13622. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13623. ktx.uploadLevels(_this._gl, !noMipmap);
  13624. _this.setCubeMapTextureParams(gl, loadMipmap);
  13625. texture.width = ktx.pixelWidth;
  13626. texture.height = ktx.pixelHeight;
  13627. texture.isReady = true;
  13628. }, undefined, undefined, true, onerror);
  13629. }
  13630. else if (isDDS) {
  13631. if (files && files.length === 6) {
  13632. this._cascadeLoadFiles(scene, function (imgs) {
  13633. var info;
  13634. var loadMipmap = false;
  13635. var width = 0;
  13636. for (var index = 0; index < imgs.length; index++) {
  13637. var data = imgs[index];
  13638. info = BABYLON.DDSTools.GetDDSInfo(data);
  13639. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13640. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13641. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13642. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13643. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13644. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13645. }
  13646. texture.width = info.width;
  13647. texture.height = info.height;
  13648. texture.type = info.textureType;
  13649. width = info.width;
  13650. }
  13651. _this.setCubeMapTextureParams(gl, loadMipmap);
  13652. texture.isReady = true;
  13653. if (onLoad) {
  13654. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13655. }
  13656. }, files, onError);
  13657. }
  13658. else {
  13659. this._loadFile(rootUrl, function (data) {
  13660. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13661. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13662. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13663. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13664. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13665. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13666. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13667. }
  13668. _this.setCubeMapTextureParams(gl, loadMipmap);
  13669. texture.width = info.width;
  13670. texture.height = info.height;
  13671. texture.isReady = true;
  13672. texture.type = info.textureType;
  13673. if (onLoad) {
  13674. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13675. }
  13676. }, undefined, undefined, true, onerror);
  13677. }
  13678. }
  13679. else {
  13680. if (!files) {
  13681. throw new Error("Cannot load cubemap because files were not defined");
  13682. }
  13683. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13684. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13685. var height = width;
  13686. _this._prepareWorkingCanvas();
  13687. if (!_this._workingCanvas || !_this._workingContext) {
  13688. return;
  13689. }
  13690. _this._workingCanvas.width = width;
  13691. _this._workingCanvas.height = height;
  13692. var faces = [
  13693. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13694. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13695. ];
  13696. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13697. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13698. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13699. for (var index = 0; index < faces.length; index++) {
  13700. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13701. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13702. }
  13703. if (!noMipmap) {
  13704. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13705. }
  13706. _this.setCubeMapTextureParams(gl, !noMipmap);
  13707. texture.width = width;
  13708. texture.height = height;
  13709. texture.isReady = true;
  13710. if (format) {
  13711. texture.format = format;
  13712. }
  13713. texture.onLoadedObservable.notifyObservers(texture);
  13714. texture.onLoadedObservable.clear();
  13715. if (onLoad) {
  13716. onLoad();
  13717. }
  13718. }, files, onError);
  13719. }
  13720. this._internalTexturesCache.push(texture);
  13721. return texture;
  13722. };
  13723. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13724. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13725. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13726. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13727. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13728. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13729. // this.resetTextureCache();
  13730. };
  13731. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13732. if (compression === void 0) { compression = null; }
  13733. if (level === void 0) { level = 0; }
  13734. texture._bufferViewArray = data;
  13735. texture.format = format;
  13736. texture.type = type;
  13737. texture.invertY = invertY;
  13738. texture._compression = compression;
  13739. var gl = this._gl;
  13740. var textureType = this._getWebGLTextureType(type);
  13741. var internalFormat = this._getInternalFormat(format);
  13742. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13743. var needConversion = false;
  13744. if (internalFormat === gl.RGB) {
  13745. internalFormat = gl.RGBA;
  13746. needConversion = true;
  13747. }
  13748. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13749. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13750. if (texture.width % 4 !== 0) {
  13751. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13752. }
  13753. // Data are known to be in +X +Y +Z -X -Y -Z
  13754. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13755. var faceData = data[faceIndex];
  13756. if (compression) {
  13757. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13758. }
  13759. else {
  13760. if (needConversion) {
  13761. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  13762. }
  13763. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  13764. }
  13765. }
  13766. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13767. if (isPot && texture.generateMipMaps && level === 0) {
  13768. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13769. }
  13770. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13771. // this.resetTextureCache();
  13772. texture.isReady = true;
  13773. };
  13774. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13775. if (compression === void 0) { compression = null; }
  13776. var gl = this._gl;
  13777. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13778. texture.isCube = true;
  13779. texture.generateMipMaps = generateMipMaps;
  13780. texture.format = format;
  13781. texture.type = type;
  13782. if (!this._doNotHandleContextLost) {
  13783. texture._bufferViewArray = data;
  13784. }
  13785. var textureType = this._getWebGLTextureType(type);
  13786. var internalFormat = this._getInternalFormat(format);
  13787. if (internalFormat === gl.RGB) {
  13788. internalFormat = gl.RGBA;
  13789. }
  13790. var width = size;
  13791. var height = width;
  13792. texture.width = width;
  13793. texture.height = height;
  13794. // Double check on POT to generate Mips.
  13795. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13796. if (!isPot) {
  13797. generateMipMaps = false;
  13798. }
  13799. // Upload data if needed. The texture won't be ready until then.
  13800. if (data) {
  13801. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13802. }
  13803. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13804. // Filters
  13805. if (data && generateMipMaps) {
  13806. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13807. }
  13808. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13809. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13810. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13811. }
  13812. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13813. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13814. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13815. }
  13816. else {
  13817. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13820. }
  13821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13822. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13823. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13824. return texture;
  13825. };
  13826. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13827. var _this = this;
  13828. if (onLoad === void 0) { onLoad = null; }
  13829. if (onError === void 0) { onError = null; }
  13830. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13831. if (invertY === void 0) { invertY = false; }
  13832. var gl = this._gl;
  13833. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13834. scene._addPendingData(texture);
  13835. texture.url = url;
  13836. this._internalTexturesCache.push(texture);
  13837. var onerror = function (request, exception) {
  13838. scene._removePendingData(texture);
  13839. if (onError && request) {
  13840. onError(request.status + " " + request.statusText, exception);
  13841. }
  13842. };
  13843. var internalCallback = function (data) {
  13844. var width = texture.width;
  13845. var faceDataArrays = callback(data);
  13846. if (!faceDataArrays) {
  13847. return;
  13848. }
  13849. if (mipmmapGenerator) {
  13850. var textureType = _this._getWebGLTextureType(type);
  13851. var internalFormat = _this._getInternalFormat(format);
  13852. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13853. var needConversion = false;
  13854. if (internalFormat === gl.RGB) {
  13855. internalFormat = gl.RGBA;
  13856. needConversion = true;
  13857. }
  13858. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13859. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13860. var mipData = mipmmapGenerator(faceDataArrays);
  13861. for (var level = 0; level < mipData.length; level++) {
  13862. var mipSize = width >> level;
  13863. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13864. var mipFaceData = mipData[level][faceIndex];
  13865. if (needConversion) {
  13866. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13867. }
  13868. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13869. }
  13870. }
  13871. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13872. }
  13873. else {
  13874. texture.generateMipMaps = !noMipmap;
  13875. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13876. }
  13877. texture.isReady = true;
  13878. // this.resetTextureCache();
  13879. scene._removePendingData(texture);
  13880. if (onLoad) {
  13881. onLoad();
  13882. }
  13883. };
  13884. this._loadFile(url, function (data) {
  13885. internalCallback(data);
  13886. }, undefined, scene.database, true, onerror);
  13887. return texture;
  13888. };
  13889. ;
  13890. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13891. if (compression === void 0) { compression = null; }
  13892. var internalFormat = this._getInternalFormat(format);
  13893. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13894. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13895. if (!this._doNotHandleContextLost) {
  13896. texture._bufferView = data;
  13897. texture.format = format;
  13898. texture.invertY = invertY;
  13899. texture._compression = compression;
  13900. }
  13901. if (texture.width % 4 !== 0) {
  13902. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13903. }
  13904. if (compression && data) {
  13905. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13906. }
  13907. else {
  13908. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13909. }
  13910. if (texture.generateMipMaps) {
  13911. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13912. }
  13913. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13914. // this.resetTextureCache();
  13915. texture.isReady = true;
  13916. };
  13917. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13918. if (compression === void 0) { compression = null; }
  13919. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13920. texture.baseWidth = width;
  13921. texture.baseHeight = height;
  13922. texture.baseDepth = depth;
  13923. texture.width = width;
  13924. texture.height = height;
  13925. texture.depth = depth;
  13926. texture.format = format;
  13927. texture.generateMipMaps = generateMipMaps;
  13928. texture.samplingMode = samplingMode;
  13929. texture.is3D = true;
  13930. if (!this._doNotHandleContextLost) {
  13931. texture._bufferView = data;
  13932. }
  13933. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13934. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13935. // Filters
  13936. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13937. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13938. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13939. if (generateMipMaps) {
  13940. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13941. }
  13942. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13943. this._internalTexturesCache.push(texture);
  13944. return texture;
  13945. };
  13946. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13947. var gl = this._gl;
  13948. if (!gl) {
  13949. return;
  13950. }
  13951. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13952. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13953. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13954. if (!noMipmap && !isCompressed) {
  13955. gl.generateMipmap(gl.TEXTURE_2D);
  13956. }
  13957. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13958. // this.resetTextureCache();
  13959. if (scene) {
  13960. scene._removePendingData(texture);
  13961. }
  13962. texture.onLoadedObservable.notifyObservers(texture);
  13963. texture.onLoadedObservable.clear();
  13964. };
  13965. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13966. var _this = this;
  13967. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13968. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13969. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13970. var gl = this._gl;
  13971. if (!gl) {
  13972. return;
  13973. }
  13974. if (!texture._webGLTexture) {
  13975. // this.resetTextureCache();
  13976. if (scene) {
  13977. scene._removePendingData(texture);
  13978. }
  13979. return;
  13980. }
  13981. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13982. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13983. texture.baseWidth = width;
  13984. texture.baseHeight = height;
  13985. texture.width = potWidth;
  13986. texture.height = potHeight;
  13987. texture.isReady = true;
  13988. if (processFunction(potWidth, potHeight, function () {
  13989. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13990. })) {
  13991. // Returning as texture needs extra async steps
  13992. return;
  13993. }
  13994. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13995. };
  13996. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13997. // Create new RGBA data container.
  13998. var rgbaData;
  13999. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14000. rgbaData = new Float32Array(width * height * 4);
  14001. }
  14002. else {
  14003. rgbaData = new Uint32Array(width * height * 4);
  14004. }
  14005. // Convert each pixel.
  14006. for (var x = 0; x < width; x++) {
  14007. for (var y = 0; y < height; y++) {
  14008. var index = (y * width + x) * 3;
  14009. var newIndex = (y * width + x) * 4;
  14010. // Map Old Value to new value.
  14011. rgbaData[newIndex + 0] = rgbData[index + 0];
  14012. rgbaData[newIndex + 1] = rgbData[index + 1];
  14013. rgbaData[newIndex + 2] = rgbData[index + 2];
  14014. // Add fully opaque alpha channel.
  14015. rgbaData[newIndex + 3] = 1;
  14016. }
  14017. }
  14018. return rgbaData;
  14019. };
  14020. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14021. var gl = this._gl;
  14022. if (texture._framebuffer) {
  14023. gl.deleteFramebuffer(texture._framebuffer);
  14024. texture._framebuffer = null;
  14025. }
  14026. if (texture._depthStencilBuffer) {
  14027. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14028. texture._depthStencilBuffer = null;
  14029. }
  14030. if (texture._MSAAFramebuffer) {
  14031. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14032. texture._MSAAFramebuffer = null;
  14033. }
  14034. if (texture._MSAARenderBuffer) {
  14035. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14036. texture._MSAARenderBuffer = null;
  14037. }
  14038. };
  14039. Engine.prototype._releaseTexture = function (texture) {
  14040. var gl = this._gl;
  14041. this._releaseFramebufferObjects(texture);
  14042. gl.deleteTexture(texture._webGLTexture);
  14043. // Unbind channels
  14044. this.unbindAllTextures();
  14045. var index = this._internalTexturesCache.indexOf(texture);
  14046. if (index !== -1) {
  14047. this._internalTexturesCache.splice(index, 1);
  14048. }
  14049. // Integrated fixed lod samplers.
  14050. if (texture._lodTextureHigh) {
  14051. texture._lodTextureHigh.dispose();
  14052. }
  14053. if (texture._lodTextureMid) {
  14054. texture._lodTextureMid.dispose();
  14055. }
  14056. if (texture._lodTextureLow) {
  14057. texture._lodTextureLow.dispose();
  14058. }
  14059. };
  14060. Engine.prototype.setProgram = function (program) {
  14061. if (this._currentProgram !== program) {
  14062. this._gl.useProgram(program);
  14063. this._currentProgram = program;
  14064. }
  14065. };
  14066. Engine.prototype.bindSamplers = function (effect) {
  14067. this.setProgram(effect.getProgram());
  14068. var samplers = effect.getSamplers();
  14069. for (var index = 0; index < samplers.length; index++) {
  14070. var uniform = effect.getUniform(samplers[index]);
  14071. if (uniform) {
  14072. this._boundUniforms[index] = uniform;
  14073. }
  14074. }
  14075. this._currentEffect = null;
  14076. };
  14077. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14078. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14079. return;
  14080. }
  14081. // Remove
  14082. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14083. // Bind last to it
  14084. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14085. // Bind to dummy
  14086. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14087. };
  14088. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14089. if (!internalTexture) {
  14090. return -1;
  14091. }
  14092. internalTexture._initialSlot = channel;
  14093. if (this.disableTextureBindingOptimization) {
  14094. if (channel !== internalTexture._designatedSlot) {
  14095. this._textureCollisions.addCount(1, false);
  14096. }
  14097. }
  14098. else {
  14099. if (channel !== internalTexture._designatedSlot) {
  14100. if (internalTexture._designatedSlot > -1) {
  14101. return internalTexture._designatedSlot;
  14102. }
  14103. else {
  14104. // No slot for this texture, let's pick a new one (if we find a free slot)
  14105. if (this._nextFreeTextureSlots.length) {
  14106. return this._nextFreeTextureSlots[0];
  14107. }
  14108. // We need to recycle the oldest bound texture, sorry.
  14109. this._textureCollisions.addCount(1, false);
  14110. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14111. }
  14112. }
  14113. }
  14114. return channel;
  14115. };
  14116. Engine.prototype._linkTrackers = function (previous, next) {
  14117. previous.next = next;
  14118. next.previous = previous;
  14119. };
  14120. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14121. var currentSlot = internalTexture._designatedSlot;
  14122. if (currentSlot === -1) {
  14123. return -1;
  14124. }
  14125. internalTexture._designatedSlot = -1;
  14126. if (this.disableTextureBindingOptimization) {
  14127. return -1;
  14128. }
  14129. // Remove from bound list
  14130. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14131. // Free the slot
  14132. this._boundTexturesCache[currentSlot] = null;
  14133. this._nextFreeTextureSlots.push(currentSlot);
  14134. return currentSlot;
  14135. };
  14136. Engine.prototype._activateCurrentTexture = function () {
  14137. if (this._currentTextureChannel !== this._activeChannel) {
  14138. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14139. this._currentTextureChannel = this._activeChannel;
  14140. }
  14141. };
  14142. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14143. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14144. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14145. this._activeChannel = texture._designatedSlot;
  14146. }
  14147. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14148. var isTextureForRendering = texture && texture._initialSlot > -1;
  14149. if (currentTextureBound !== texture) {
  14150. if (currentTextureBound) {
  14151. this._removeDesignatedSlot(currentTextureBound);
  14152. }
  14153. this._activateCurrentTexture();
  14154. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14155. this._boundTexturesCache[this._activeChannel] = texture;
  14156. if (texture) {
  14157. if (!this.disableTextureBindingOptimization) {
  14158. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14159. if (slotIndex > -1) {
  14160. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14161. }
  14162. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14163. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14164. }
  14165. texture._designatedSlot = this._activeChannel;
  14166. }
  14167. }
  14168. else if (forTextureDataUpdate) {
  14169. this._activateCurrentTexture();
  14170. }
  14171. if (isTextureForRendering && !forTextureDataUpdate) {
  14172. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14173. }
  14174. };
  14175. Engine.prototype._bindTexture = function (channel, texture) {
  14176. if (channel < 0) {
  14177. return;
  14178. }
  14179. if (texture) {
  14180. channel = this._getCorrectTextureChannel(channel, texture);
  14181. }
  14182. this._activeChannel = channel;
  14183. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14184. };
  14185. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14186. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14187. };
  14188. Engine.prototype.unbindAllTextures = function () {
  14189. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14190. this._activeChannel = channel;
  14191. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14192. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14193. if (this.webGLVersion > 1) {
  14194. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14195. }
  14196. }
  14197. };
  14198. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14199. if (channel < 0) {
  14200. return;
  14201. }
  14202. if (uniform) {
  14203. this._boundUniforms[channel] = uniform;
  14204. }
  14205. this._setTexture(channel, texture);
  14206. };
  14207. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14208. var uniform = this._boundUniforms[sourceSlot];
  14209. if (uniform._currentState === destination) {
  14210. return;
  14211. }
  14212. this._gl.uniform1i(uniform, destination);
  14213. uniform._currentState = destination;
  14214. };
  14215. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14216. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14217. // Not ready?
  14218. if (!texture) {
  14219. if (this._boundTexturesCache[channel] != null) {
  14220. this._activeChannel = channel;
  14221. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14222. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14223. if (this.webGLVersion > 1) {
  14224. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14225. }
  14226. }
  14227. return false;
  14228. }
  14229. // Video
  14230. if (texture.video) {
  14231. this._activeChannel = channel;
  14232. texture.update();
  14233. }
  14234. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14235. texture.delayLoad();
  14236. return false;
  14237. }
  14238. var internalTexture;
  14239. if (texture.isReady()) {
  14240. internalTexture = texture.getInternalTexture();
  14241. }
  14242. else if (texture.isCube) {
  14243. internalTexture = this.emptyCubeTexture;
  14244. }
  14245. else if (texture.is3D) {
  14246. internalTexture = this.emptyTexture3D;
  14247. }
  14248. else {
  14249. internalTexture = this.emptyTexture;
  14250. }
  14251. if (!isPartOfTextureArray) {
  14252. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14253. }
  14254. if (this._boundTexturesCache[channel] === internalTexture) {
  14255. this._moveBoundTextureOnTop(internalTexture);
  14256. if (!isPartOfTextureArray) {
  14257. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14258. }
  14259. return false;
  14260. }
  14261. this._activeChannel = channel;
  14262. if (internalTexture && internalTexture.is3D) {
  14263. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14264. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14265. internalTexture._cachedWrapU = texture.wrapU;
  14266. switch (texture.wrapU) {
  14267. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14268. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14269. break;
  14270. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14271. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14272. break;
  14273. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14274. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14275. break;
  14276. }
  14277. }
  14278. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14279. internalTexture._cachedWrapV = texture.wrapV;
  14280. switch (texture.wrapV) {
  14281. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14282. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14283. break;
  14284. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14285. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14286. break;
  14287. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14288. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14289. break;
  14290. }
  14291. }
  14292. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14293. internalTexture._cachedWrapR = texture.wrapR;
  14294. switch (texture.wrapR) {
  14295. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14296. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14297. break;
  14298. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14299. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14300. break;
  14301. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14302. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14303. break;
  14304. }
  14305. }
  14306. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14307. }
  14308. else if (internalTexture && internalTexture.isCube) {
  14309. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14310. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14311. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14312. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14313. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14314. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14315. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14316. }
  14317. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14318. }
  14319. else {
  14320. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14321. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14322. internalTexture._cachedWrapU = texture.wrapU;
  14323. switch (texture.wrapU) {
  14324. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14325. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14326. break;
  14327. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14328. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14329. break;
  14330. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14332. break;
  14333. }
  14334. }
  14335. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14336. internalTexture._cachedWrapV = texture.wrapV;
  14337. switch (texture.wrapV) {
  14338. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14339. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14340. break;
  14341. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14342. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14343. break;
  14344. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14345. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14346. break;
  14347. }
  14348. }
  14349. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14350. }
  14351. return true;
  14352. };
  14353. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14354. if (channel < 0 || !uniform) {
  14355. return;
  14356. }
  14357. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14358. this._textureUnits = new Int32Array(textures.length);
  14359. }
  14360. for (var i = 0; i < textures.length; i++) {
  14361. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14362. }
  14363. this._gl.uniform1iv(uniform, this._textureUnits);
  14364. for (var index = 0; index < textures.length; index++) {
  14365. this._setTexture(this._textureUnits[index], textures[index], true);
  14366. }
  14367. };
  14368. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14369. var internalTexture = texture.getInternalTexture();
  14370. if (!internalTexture) {
  14371. return;
  14372. }
  14373. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14374. var value = texture.anisotropicFilteringLevel;
  14375. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14376. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14377. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14378. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14379. }
  14380. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14381. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14382. internalTexture._cachedAnisotropicFilteringLevel = value;
  14383. }
  14384. };
  14385. Engine.prototype.readPixels = function (x, y, width, height) {
  14386. var data = new Uint8Array(height * width * 4);
  14387. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14388. return data;
  14389. };
  14390. /**
  14391. * Add an externaly attached data from its key.
  14392. * This method call will fail and return false, if such key already exists.
  14393. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14394. * @param key the unique key that identifies the data
  14395. * @param data the data object to associate to the key for this Engine instance
  14396. * @return true if no such key were already present and the data was added successfully, false otherwise
  14397. */
  14398. Engine.prototype.addExternalData = function (key, data) {
  14399. if (!this._externalData) {
  14400. this._externalData = new BABYLON.StringDictionary();
  14401. }
  14402. return this._externalData.add(key, data);
  14403. };
  14404. /**
  14405. * Get an externaly attached data from its key
  14406. * @param key the unique key that identifies the data
  14407. * @return the associated data, if present (can be null), or undefined if not present
  14408. */
  14409. Engine.prototype.getExternalData = function (key) {
  14410. if (!this._externalData) {
  14411. this._externalData = new BABYLON.StringDictionary();
  14412. }
  14413. return this._externalData.get(key);
  14414. };
  14415. /**
  14416. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14417. * @param key the unique key that identifies the data
  14418. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14419. * @return the associated data, can be null if the factory returned null.
  14420. */
  14421. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14422. if (!this._externalData) {
  14423. this._externalData = new BABYLON.StringDictionary();
  14424. }
  14425. return this._externalData.getOrAddWithFactory(key, factory);
  14426. };
  14427. /**
  14428. * Remove an externaly attached data from the Engine instance
  14429. * @param key the unique key that identifies the data
  14430. * @return true if the data was successfully removed, false if it doesn't exist
  14431. */
  14432. Engine.prototype.removeExternalData = function (key) {
  14433. if (!this._externalData) {
  14434. this._externalData = new BABYLON.StringDictionary();
  14435. }
  14436. return this._externalData.remove(key);
  14437. };
  14438. Engine.prototype.unbindAllAttributes = function () {
  14439. if (this._mustWipeVertexAttributes) {
  14440. this._mustWipeVertexAttributes = false;
  14441. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14442. this._gl.disableVertexAttribArray(i);
  14443. this._vertexAttribArraysEnabled[i] = false;
  14444. this._currentBufferPointers[i].active = false;
  14445. }
  14446. return;
  14447. }
  14448. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14449. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14450. continue;
  14451. }
  14452. this._gl.disableVertexAttribArray(i);
  14453. this._vertexAttribArraysEnabled[i] = false;
  14454. this._currentBufferPointers[i].active = false;
  14455. }
  14456. };
  14457. Engine.prototype.releaseEffects = function () {
  14458. for (var name in this._compiledEffects) {
  14459. this._deleteProgram(this._compiledEffects[name]._program);
  14460. }
  14461. this._compiledEffects = {};
  14462. };
  14463. // Dispose
  14464. Engine.prototype.dispose = function () {
  14465. this.hideLoadingUI();
  14466. this.stopRenderLoop();
  14467. // Release postProcesses
  14468. while (this.postProcesses.length) {
  14469. this.postProcesses[0].dispose();
  14470. }
  14471. // Empty texture
  14472. if (this._emptyTexture) {
  14473. this._releaseTexture(this._emptyTexture);
  14474. this._emptyTexture = null;
  14475. }
  14476. if (this._emptyCubeTexture) {
  14477. this._releaseTexture(this._emptyCubeTexture);
  14478. this._emptyCubeTexture = null;
  14479. }
  14480. // Rescale PP
  14481. if (this._rescalePostProcess) {
  14482. this._rescalePostProcess.dispose();
  14483. }
  14484. // Release scenes
  14485. while (this.scenes.length) {
  14486. this.scenes[0].dispose();
  14487. }
  14488. // Release audio engine
  14489. if (Engine.audioEngine) {
  14490. Engine.audioEngine.dispose();
  14491. }
  14492. // Release effects
  14493. this.releaseEffects();
  14494. // Unbind
  14495. this.unbindAllAttributes();
  14496. if (this._dummyFramebuffer) {
  14497. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14498. }
  14499. //WebVR
  14500. this.disableVR();
  14501. // Events
  14502. if (BABYLON.Tools.IsWindowObjectExist()) {
  14503. window.removeEventListener("blur", this._onBlur);
  14504. window.removeEventListener("focus", this._onFocus);
  14505. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14506. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14507. if (this._renderingCanvas) {
  14508. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14509. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14510. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14511. if (!this._doNotHandleContextLost) {
  14512. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14513. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14514. }
  14515. }
  14516. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14517. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14518. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14519. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14520. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14521. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14522. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14523. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14524. if (this._onVrDisplayConnect) {
  14525. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14526. if (this._onVrDisplayDisconnect) {
  14527. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14528. }
  14529. if (this._onVrDisplayPresentChange) {
  14530. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14531. }
  14532. this._onVrDisplayConnect = null;
  14533. this._onVrDisplayDisconnect = null;
  14534. }
  14535. }
  14536. // Remove from Instances
  14537. var index = Engine.Instances.indexOf(this);
  14538. if (index >= 0) {
  14539. Engine.Instances.splice(index, 1);
  14540. }
  14541. this._workingCanvas = null;
  14542. this._workingContext = null;
  14543. this._currentBufferPointers = [];
  14544. this._renderingCanvas = null;
  14545. this._currentProgram = null;
  14546. this.onResizeObservable.clear();
  14547. this.onCanvasBlurObservable.clear();
  14548. this.onCanvasFocusObservable.clear();
  14549. this.onCanvasPointerOutObservable.clear();
  14550. this.onBeginFrameObservable.clear();
  14551. this.onEndFrameObservable.clear();
  14552. BABYLON.Effect.ResetCache();
  14553. // Abort active requests
  14554. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14555. var request = _a[_i];
  14556. request.abort();
  14557. }
  14558. };
  14559. // Loading screen
  14560. Engine.prototype.displayLoadingUI = function () {
  14561. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14562. return;
  14563. }
  14564. var loadingScreen = this.loadingScreen;
  14565. if (loadingScreen) {
  14566. loadingScreen.displayLoadingUI();
  14567. }
  14568. };
  14569. Engine.prototype.hideLoadingUI = function () {
  14570. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14571. return;
  14572. }
  14573. var loadingScreen = this.loadingScreen;
  14574. if (loadingScreen) {
  14575. loadingScreen.hideLoadingUI();
  14576. }
  14577. };
  14578. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14579. get: function () {
  14580. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14581. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14582. return this._loadingScreen;
  14583. },
  14584. set: function (loadingScreen) {
  14585. this._loadingScreen = loadingScreen;
  14586. },
  14587. enumerable: true,
  14588. configurable: true
  14589. });
  14590. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14591. set: function (text) {
  14592. this.loadingScreen.loadingUIText = text;
  14593. },
  14594. enumerable: true,
  14595. configurable: true
  14596. });
  14597. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14598. set: function (color) {
  14599. this.loadingScreen.loadingUIBackgroundColor = color;
  14600. },
  14601. enumerable: true,
  14602. configurable: true
  14603. });
  14604. Engine.prototype.attachContextLostEvent = function (callback) {
  14605. if (this._renderingCanvas) {
  14606. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14607. }
  14608. };
  14609. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14610. if (this._renderingCanvas) {
  14611. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14612. }
  14613. };
  14614. Engine.prototype.getVertexShaderSource = function (program) {
  14615. var shaders = this._gl.getAttachedShaders(program);
  14616. if (!shaders) {
  14617. return null;
  14618. }
  14619. return this._gl.getShaderSource(shaders[0]);
  14620. };
  14621. Engine.prototype.getFragmentShaderSource = function (program) {
  14622. var shaders = this._gl.getAttachedShaders(program);
  14623. if (!shaders) {
  14624. return null;
  14625. }
  14626. return this._gl.getShaderSource(shaders[1]);
  14627. };
  14628. Engine.prototype.getError = function () {
  14629. return this._gl.getError();
  14630. };
  14631. // FPS
  14632. Engine.prototype.getFps = function () {
  14633. return this._fps;
  14634. };
  14635. Engine.prototype.getDeltaTime = function () {
  14636. return this._deltaTime;
  14637. };
  14638. Engine.prototype._measureFps = function () {
  14639. this._performanceMonitor.sampleFrame();
  14640. this._fps = this._performanceMonitor.averageFPS;
  14641. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14642. };
  14643. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14644. if (faceIndex === void 0) { faceIndex = -1; }
  14645. var gl = this._gl;
  14646. if (!this._dummyFramebuffer) {
  14647. var dummy = gl.createFramebuffer();
  14648. if (!dummy) {
  14649. throw new Error("Unable to create dummy framebuffer");
  14650. }
  14651. this._dummyFramebuffer = dummy;
  14652. }
  14653. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14654. if (faceIndex > -1) {
  14655. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14656. }
  14657. else {
  14658. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14659. }
  14660. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14661. var buffer;
  14662. switch (readType) {
  14663. case gl.UNSIGNED_BYTE:
  14664. buffer = new Uint8Array(4 * width * height);
  14665. readType = gl.UNSIGNED_BYTE;
  14666. break;
  14667. default:
  14668. buffer = new Float32Array(4 * width * height);
  14669. readType = gl.FLOAT;
  14670. break;
  14671. }
  14672. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14673. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14674. return buffer;
  14675. };
  14676. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14677. if (this._webGLVersion > 1) {
  14678. return this._caps.colorBufferFloat;
  14679. }
  14680. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14681. };
  14682. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14683. if (this._webGLVersion > 1) {
  14684. return this._caps.colorBufferFloat;
  14685. }
  14686. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14687. };
  14688. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14689. Engine.prototype._canRenderToFramebuffer = function (type) {
  14690. var gl = this._gl;
  14691. //clear existing errors
  14692. while (gl.getError() !== gl.NO_ERROR) { }
  14693. var successful = true;
  14694. var texture = gl.createTexture();
  14695. gl.bindTexture(gl.TEXTURE_2D, texture);
  14696. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14697. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14698. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14699. var fb = gl.createFramebuffer();
  14700. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14701. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14702. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14703. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14704. successful = successful && (gl.getError() === gl.NO_ERROR);
  14705. //try render by clearing frame buffer's color buffer
  14706. if (successful) {
  14707. gl.clear(gl.COLOR_BUFFER_BIT);
  14708. successful = successful && (gl.getError() === gl.NO_ERROR);
  14709. }
  14710. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14711. if (successful) {
  14712. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14713. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14714. var readFormat = gl.RGBA;
  14715. var readType = gl.UNSIGNED_BYTE;
  14716. var buffer = new Uint8Array(4);
  14717. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14718. successful = successful && (gl.getError() === gl.NO_ERROR);
  14719. }
  14720. //clean up
  14721. gl.deleteTexture(texture);
  14722. gl.deleteFramebuffer(fb);
  14723. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14724. //clear accumulated errors
  14725. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14726. return successful;
  14727. };
  14728. Engine.prototype._getWebGLTextureType = function (type) {
  14729. if (type === Engine.TEXTURETYPE_FLOAT) {
  14730. return this._gl.FLOAT;
  14731. }
  14732. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14733. // Add Half Float Constant.
  14734. return this._gl.HALF_FLOAT_OES;
  14735. }
  14736. return this._gl.UNSIGNED_BYTE;
  14737. };
  14738. ;
  14739. /** @ignore */
  14740. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  14741. if (this._webGLVersion === 1) {
  14742. return this._gl.RGBA;
  14743. }
  14744. if (type === Engine.TEXTURETYPE_FLOAT) {
  14745. if (format) {
  14746. switch (format) {
  14747. case Engine.TEXTUREFORMAT_R32F:
  14748. return this._gl.R32F;
  14749. case Engine.TEXTUREFORMAT_RG32F:
  14750. return this._gl.RG32F;
  14751. case Engine.TEXTUREFORMAT_RGB32F:
  14752. return this._gl.RGB32F;
  14753. }
  14754. }
  14755. return this._gl.RGBA32F;
  14756. }
  14757. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14758. return this._gl.RGBA16F;
  14759. }
  14760. return this._gl.RGBA;
  14761. };
  14762. ;
  14763. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  14764. if (type === Engine.TEXTURETYPE_FLOAT) {
  14765. return this._gl.RGBA32F;
  14766. }
  14767. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14768. return this._gl.RGBA16F;
  14769. }
  14770. return this._gl.RGBA8;
  14771. };
  14772. ;
  14773. Engine.prototype.createQuery = function () {
  14774. return this._gl.createQuery();
  14775. };
  14776. Engine.prototype.deleteQuery = function (query) {
  14777. this._gl.deleteQuery(query);
  14778. return this;
  14779. };
  14780. Engine.prototype.isQueryResultAvailable = function (query) {
  14781. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  14782. };
  14783. Engine.prototype.getQueryResult = function (query) {
  14784. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14785. };
  14786. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14787. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14788. this._gl.beginQuery(glAlgorithm, query);
  14789. return this;
  14790. };
  14791. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14792. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14793. this._gl.endQuery(glAlgorithm);
  14794. return this;
  14795. };
  14796. /* Time queries */
  14797. Engine.prototype._createTimeQuery = function () {
  14798. var timerQuery = this._caps.timerQuery;
  14799. if (timerQuery.createQueryEXT) {
  14800. return timerQuery.createQueryEXT();
  14801. }
  14802. return this.createQuery();
  14803. };
  14804. Engine.prototype._deleteTimeQuery = function (query) {
  14805. var timerQuery = this._caps.timerQuery;
  14806. if (timerQuery.deleteQueryEXT) {
  14807. timerQuery.deleteQueryEXT(query);
  14808. return;
  14809. }
  14810. this.deleteQuery(query);
  14811. };
  14812. Engine.prototype._getTimeQueryResult = function (query) {
  14813. var timerQuery = this._caps.timerQuery;
  14814. if (timerQuery.getQueryObjectEXT) {
  14815. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14816. }
  14817. return this.getQueryResult(query);
  14818. };
  14819. Engine.prototype._getTimeQueryAvailability = function (query) {
  14820. var timerQuery = this._caps.timerQuery;
  14821. if (timerQuery.getQueryObjectEXT) {
  14822. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14823. }
  14824. return this.isQueryResultAvailable(query);
  14825. };
  14826. Engine.prototype.startTimeQuery = function () {
  14827. var timerQuery = this._caps.timerQuery;
  14828. if (!timerQuery) {
  14829. return null;
  14830. }
  14831. var token = new BABYLON._TimeToken();
  14832. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14833. if (this._caps.canUseTimestampForTimerQuery) {
  14834. token._startTimeQuery = this._createTimeQuery();
  14835. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14836. }
  14837. else {
  14838. if (this._currentNonTimestampToken) {
  14839. return this._currentNonTimestampToken;
  14840. }
  14841. token._timeElapsedQuery = this._createTimeQuery();
  14842. if (timerQuery.beginQueryEXT) {
  14843. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14844. }
  14845. else {
  14846. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14847. }
  14848. this._currentNonTimestampToken = token;
  14849. }
  14850. return token;
  14851. };
  14852. Engine.prototype.endTimeQuery = function (token) {
  14853. var timerQuery = this._caps.timerQuery;
  14854. if (!timerQuery || !token) {
  14855. return -1;
  14856. }
  14857. if (this._caps.canUseTimestampForTimerQuery) {
  14858. if (!token._startTimeQuery) {
  14859. return -1;
  14860. }
  14861. if (!token._endTimeQuery) {
  14862. token._endTimeQuery = this._createTimeQuery();
  14863. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14864. }
  14865. }
  14866. else if (!token._timeElapsedQueryEnded) {
  14867. if (!token._timeElapsedQuery) {
  14868. return -1;
  14869. }
  14870. if (timerQuery.endQueryEXT) {
  14871. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14872. }
  14873. else {
  14874. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14875. }
  14876. token._timeElapsedQueryEnded = true;
  14877. }
  14878. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14879. var available = false;
  14880. if (token._endTimeQuery) {
  14881. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14882. }
  14883. else if (token._timeElapsedQuery) {
  14884. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14885. }
  14886. if (available && !disjoint) {
  14887. var result = 0;
  14888. if (this._caps.canUseTimestampForTimerQuery) {
  14889. if (!token._startTimeQuery || !token._endTimeQuery) {
  14890. return -1;
  14891. }
  14892. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14893. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14894. result = timeEnd - timeStart;
  14895. this._deleteTimeQuery(token._startTimeQuery);
  14896. this._deleteTimeQuery(token._endTimeQuery);
  14897. token._startTimeQuery = null;
  14898. token._endTimeQuery = null;
  14899. }
  14900. else {
  14901. if (!token._timeElapsedQuery) {
  14902. return -1;
  14903. }
  14904. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14905. this._deleteTimeQuery(token._timeElapsedQuery);
  14906. token._timeElapsedQuery = null;
  14907. token._timeElapsedQueryEnded = false;
  14908. this._currentNonTimestampToken = null;
  14909. }
  14910. return result;
  14911. }
  14912. return -1;
  14913. };
  14914. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14915. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14916. };
  14917. // Transform feedback
  14918. Engine.prototype.createTransformFeedback = function () {
  14919. return this._gl.createTransformFeedback();
  14920. };
  14921. Engine.prototype.deleteTransformFeedback = function (value) {
  14922. this._gl.deleteTransformFeedback(value);
  14923. };
  14924. Engine.prototype.bindTransformFeedback = function (value) {
  14925. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14926. };
  14927. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14928. if (usePoints === void 0) { usePoints = true; }
  14929. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14930. };
  14931. Engine.prototype.endTransformFeedback = function () {
  14932. this._gl.endTransformFeedback();
  14933. };
  14934. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14935. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14936. };
  14937. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14938. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14939. };
  14940. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14941. var _this = this;
  14942. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14943. this._activeRequests.push(request);
  14944. request.onCompleteObservable.add(function (request) {
  14945. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14946. });
  14947. return request;
  14948. };
  14949. /** @ignore */
  14950. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14951. var _this = this;
  14952. return new Promise(function (resolve, reject) {
  14953. _this._loadFile(url, function (data) {
  14954. resolve(data);
  14955. }, undefined, database, useArrayBuffer, function (request, exception) {
  14956. reject(exception);
  14957. });
  14958. });
  14959. };
  14960. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14961. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14962. var onload = function (data) {
  14963. loadedFiles[index] = data;
  14964. loadedFiles._internalCount++;
  14965. if (loadedFiles._internalCount === 6) {
  14966. onfinish(loadedFiles);
  14967. }
  14968. };
  14969. var onerror = function (request, exception) {
  14970. if (onErrorCallBack && request) {
  14971. onErrorCallBack(request.status + " " + request.statusText, exception);
  14972. }
  14973. };
  14974. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14975. };
  14976. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  14977. if (onError === void 0) { onError = null; }
  14978. var loadedFiles = [];
  14979. loadedFiles._internalCount = 0;
  14980. for (var index = 0; index < 6; index++) {
  14981. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14982. }
  14983. };
  14984. // Statics
  14985. Engine.isSupported = function () {
  14986. try {
  14987. var tempcanvas = document.createElement("canvas");
  14988. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14989. return gl != null && !!window.WebGLRenderingContext;
  14990. }
  14991. catch (e) {
  14992. return false;
  14993. }
  14994. };
  14995. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14996. Engine.ExceptionList = [
  14997. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14998. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14999. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15000. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15001. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15002. ];
  15003. Engine.Instances = new Array();
  15004. // Const statics
  15005. Engine._ALPHA_DISABLE = 0;
  15006. Engine._ALPHA_ADD = 1;
  15007. Engine._ALPHA_COMBINE = 2;
  15008. Engine._ALPHA_SUBTRACT = 3;
  15009. Engine._ALPHA_MULTIPLY = 4;
  15010. Engine._ALPHA_MAXIMIZED = 5;
  15011. Engine._ALPHA_ONEONE = 6;
  15012. Engine._ALPHA_PREMULTIPLIED = 7;
  15013. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15014. Engine._ALPHA_INTERPOLATE = 9;
  15015. Engine._ALPHA_SCREENMODE = 10;
  15016. Engine._DELAYLOADSTATE_NONE = 0;
  15017. Engine._DELAYLOADSTATE_LOADED = 1;
  15018. Engine._DELAYLOADSTATE_LOADING = 2;
  15019. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15020. Engine._TEXTUREFORMAT_ALPHA = 0;
  15021. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15022. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15023. Engine._TEXTUREFORMAT_RGB = 4;
  15024. Engine._TEXTUREFORMAT_RGBA = 5;
  15025. Engine._TEXTUREFORMAT_R32F = 6;
  15026. Engine._TEXTUREFORMAT_RG32F = 7;
  15027. Engine._TEXTUREFORMAT_RGB32F = 8;
  15028. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15029. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15030. Engine._TEXTURETYPE_FLOAT = 1;
  15031. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15032. // Depht or Stencil test Constants.
  15033. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15034. 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.
  15035. 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.
  15036. 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.
  15037. 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.
  15038. 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.
  15039. 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.
  15040. 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.
  15041. // Stencil Actions Constants.
  15042. Engine._KEEP = 0x1E00;
  15043. Engine._REPLACE = 0x1E01;
  15044. Engine._INCR = 0x1E02;
  15045. Engine._DECR = 0x1E03;
  15046. Engine._INVERT = 0x150A;
  15047. Engine._INCR_WRAP = 0x8507;
  15048. Engine._DECR_WRAP = 0x8508;
  15049. // Texture rescaling mode
  15050. Engine._SCALEMODE_FLOOR = 1;
  15051. Engine._SCALEMODE_NEAREST = 2;
  15052. Engine._SCALEMODE_CEILING = 3;
  15053. // Updatable statics so stick with vars here
  15054. Engine.CollisionsEpsilon = 0.001;
  15055. Engine.CodeRepository = "src/";
  15056. Engine.ShadersRepository = "src/Shaders/";
  15057. return Engine;
  15058. }());
  15059. BABYLON.Engine = Engine;
  15060. })(BABYLON || (BABYLON = {}));
  15061. //# sourceMappingURL=babylon.engine.js.map
  15062. var BABYLON;
  15063. (function (BABYLON) {
  15064. /**
  15065. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15066. */
  15067. var Node = /** @class */ (function () {
  15068. /**
  15069. * Creates a new Node
  15070. * @param {string} name - the name and id to be given to this node
  15071. * @param {BABYLON.Scene} the scene this node will be added to
  15072. */
  15073. function Node(name, scene) {
  15074. if (scene === void 0) { scene = null; }
  15075. /**
  15076. * Gets or sets a string used to store user defined state for the node
  15077. */
  15078. this.state = "";
  15079. /**
  15080. * Gets or sets an object used to store user defined information for the node
  15081. */
  15082. this.metadata = null;
  15083. /**
  15084. * Gets or sets a boolean used to define if the node must be serialized
  15085. */
  15086. this.doNotSerialize = false;
  15087. /** @ignore */
  15088. this._isDisposed = false;
  15089. /**
  15090. * Gets a list of {BABYLON.Animation} associated with the node
  15091. */
  15092. this.animations = new Array();
  15093. this._ranges = {};
  15094. this._isEnabled = true;
  15095. this._isReady = true;
  15096. /** @ignore */
  15097. this._currentRenderId = -1;
  15098. this._parentRenderId = -1;
  15099. /**
  15100. * An event triggered when the mesh is disposed
  15101. * @type {BABYLON.Observable}
  15102. */
  15103. this.onDisposeObservable = new BABYLON.Observable();
  15104. // Behaviors
  15105. this._behaviors = new Array();
  15106. this.name = name;
  15107. this.id = name;
  15108. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15109. this.uniqueId = this._scene.getUniqueId();
  15110. this._initCache();
  15111. }
  15112. /**
  15113. * Gets a boolean indicating if the node has been disposed
  15114. * @returns true if the node was disposed
  15115. */
  15116. Node.prototype.isDisposed = function () {
  15117. return this._isDisposed;
  15118. };
  15119. Object.defineProperty(Node.prototype, "parent", {
  15120. get: function () {
  15121. return this._parentNode;
  15122. },
  15123. /**
  15124. * Gets or sets the parent of the node
  15125. */
  15126. set: function (parent) {
  15127. if (this._parentNode === parent) {
  15128. return;
  15129. }
  15130. // Remove self from list of children of parent
  15131. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15132. var index = this._parentNode._children.indexOf(this);
  15133. if (index !== -1) {
  15134. this._parentNode._children.splice(index, 1);
  15135. }
  15136. }
  15137. // Store new parent
  15138. this._parentNode = parent;
  15139. // Add as child to new parent
  15140. if (this._parentNode) {
  15141. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15142. this._parentNode._children = new Array();
  15143. }
  15144. this._parentNode._children.push(this);
  15145. }
  15146. },
  15147. enumerable: true,
  15148. configurable: true
  15149. });
  15150. /**
  15151. * Gets a string idenfifying the name of the class
  15152. * @returns "Node" string
  15153. */
  15154. Node.prototype.getClassName = function () {
  15155. return "Node";
  15156. };
  15157. Object.defineProperty(Node.prototype, "onDispose", {
  15158. /**
  15159. * Sets a callback that will be raised when the node will be disposed
  15160. */
  15161. set: function (callback) {
  15162. if (this._onDisposeObserver) {
  15163. this.onDisposeObservable.remove(this._onDisposeObserver);
  15164. }
  15165. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15166. },
  15167. enumerable: true,
  15168. configurable: true
  15169. });
  15170. /**
  15171. * Gets the scene of the node
  15172. * @returns a {BABYLON.Scene}
  15173. */
  15174. Node.prototype.getScene = function () {
  15175. return this._scene;
  15176. };
  15177. /**
  15178. * Gets the engine of the node
  15179. * @returns a {BABYLON.Engine}
  15180. */
  15181. Node.prototype.getEngine = function () {
  15182. return this._scene.getEngine();
  15183. };
  15184. /**
  15185. * Attach a behavior to the node
  15186. * @see http://doc.babylonjs.com/features/behaviour
  15187. * @param behavior defines the behavior to attach
  15188. * @returns the current Node
  15189. */
  15190. Node.prototype.addBehavior = function (behavior) {
  15191. var _this = this;
  15192. var index = this._behaviors.indexOf(behavior);
  15193. if (index !== -1) {
  15194. return this;
  15195. }
  15196. behavior.init();
  15197. if (this._scene.isLoading) {
  15198. // We defer the attach when the scene will be loaded
  15199. var observer = this._scene.onDataLoadedObservable.add(function () {
  15200. behavior.attach(_this);
  15201. setTimeout(function () {
  15202. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15203. _this._scene.onDataLoadedObservable.remove(observer);
  15204. }, 0);
  15205. });
  15206. }
  15207. else {
  15208. behavior.attach(this);
  15209. }
  15210. this._behaviors.push(behavior);
  15211. return this;
  15212. };
  15213. /**
  15214. * Remove an attached behavior
  15215. * @see http://doc.babylonjs.com/features/behaviour
  15216. * @param behavior defines the behavior to attach
  15217. * @returns the current Node
  15218. */
  15219. Node.prototype.removeBehavior = function (behavior) {
  15220. var index = this._behaviors.indexOf(behavior);
  15221. if (index === -1) {
  15222. return this;
  15223. }
  15224. this._behaviors[index].detach();
  15225. this._behaviors.splice(index, 1);
  15226. return this;
  15227. };
  15228. Object.defineProperty(Node.prototype, "behaviors", {
  15229. /**
  15230. * Gets the list of attached behaviors
  15231. * @see http://doc.babylonjs.com/features/behaviour
  15232. */
  15233. get: function () {
  15234. return this._behaviors;
  15235. },
  15236. enumerable: true,
  15237. configurable: true
  15238. });
  15239. /**
  15240. * Gets an attached behavior by name
  15241. * @param name defines the name of the behavior to look for
  15242. * @see http://doc.babylonjs.com/features/behaviour
  15243. * @returns null if behavior was not found else the requested behavior
  15244. */
  15245. Node.prototype.getBehaviorByName = function (name) {
  15246. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15247. var behavior = _a[_i];
  15248. if (behavior.name === name) {
  15249. return behavior;
  15250. }
  15251. }
  15252. return null;
  15253. };
  15254. /**
  15255. * Returns the world matrix of the node
  15256. * @returns a matrix containing the node's world matrix
  15257. */
  15258. Node.prototype.getWorldMatrix = function () {
  15259. return BABYLON.Matrix.Identity();
  15260. };
  15261. // override it in derived class if you add new variables to the cache
  15262. // and call the parent class method
  15263. /** @ignore */
  15264. Node.prototype._initCache = function () {
  15265. this._cache = {};
  15266. this._cache.parent = undefined;
  15267. };
  15268. /** @ignore */
  15269. Node.prototype.updateCache = function (force) {
  15270. if (!force && this.isSynchronized())
  15271. return;
  15272. this._cache.parent = this.parent;
  15273. this._updateCache();
  15274. };
  15275. // override it in derived class if you add new variables to the cache
  15276. // and call the parent class method if !ignoreParentClass
  15277. /** @ignore */
  15278. Node.prototype._updateCache = function (ignoreParentClass) {
  15279. };
  15280. // override it in derived class if you add new variables to the cache
  15281. /** @ignore */
  15282. Node.prototype._isSynchronized = function () {
  15283. return true;
  15284. };
  15285. /** @ignore */
  15286. Node.prototype._markSyncedWithParent = function () {
  15287. if (this.parent) {
  15288. this._parentRenderId = this.parent._currentRenderId;
  15289. }
  15290. };
  15291. /** @ignore */
  15292. Node.prototype.isSynchronizedWithParent = function () {
  15293. if (!this.parent) {
  15294. return true;
  15295. }
  15296. if (this._parentRenderId !== this.parent._currentRenderId) {
  15297. return false;
  15298. }
  15299. return this.parent.isSynchronized();
  15300. };
  15301. /** @ignore */
  15302. Node.prototype.isSynchronized = function (updateCache) {
  15303. var check = this.hasNewParent();
  15304. check = check || !this.isSynchronizedWithParent();
  15305. check = check || !this._isSynchronized();
  15306. if (updateCache)
  15307. this.updateCache(true);
  15308. return !check;
  15309. };
  15310. /** @ignore */
  15311. Node.prototype.hasNewParent = function (update) {
  15312. if (this._cache.parent === this.parent)
  15313. return false;
  15314. if (update)
  15315. this._cache.parent = this.parent;
  15316. return true;
  15317. };
  15318. /**
  15319. * Is this node ready to be used/rendered
  15320. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15321. * @return true if the node is ready
  15322. */
  15323. Node.prototype.isReady = function (completeCheck) {
  15324. if (completeCheck === void 0) { completeCheck = false; }
  15325. return this._isReady;
  15326. };
  15327. /**
  15328. * Is this node enabled?
  15329. * 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
  15330. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  15331. * @return whether this node (and its parent) is enabled
  15332. * @see setEnabled
  15333. */
  15334. Node.prototype.isEnabled = function (checkAncestors) {
  15335. if (checkAncestors === void 0) { checkAncestors = true; }
  15336. if (checkAncestors === false) {
  15337. return this._isEnabled;
  15338. }
  15339. if (this._isEnabled === false) {
  15340. return false;
  15341. }
  15342. if (this.parent !== undefined && this.parent !== null) {
  15343. return this.parent.isEnabled(checkAncestors);
  15344. }
  15345. return true;
  15346. };
  15347. /**
  15348. * Set the enabled state of this node
  15349. * @param value defines the new enabled state
  15350. * @see isEnabled
  15351. */
  15352. Node.prototype.setEnabled = function (value) {
  15353. this._isEnabled = value;
  15354. };
  15355. /**
  15356. * Is this node a descendant of the given node?
  15357. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15358. * @param ancestor defines the parent node to inspect
  15359. * @see parent
  15360. * @returns a boolean indicating if this node is a descendant of the given node
  15361. */
  15362. Node.prototype.isDescendantOf = function (ancestor) {
  15363. if (this.parent) {
  15364. if (this.parent === ancestor) {
  15365. return true;
  15366. }
  15367. return this.parent.isDescendantOf(ancestor);
  15368. }
  15369. return false;
  15370. };
  15371. /** @ignore */
  15372. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15373. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15374. if (!this._children) {
  15375. return;
  15376. }
  15377. for (var index = 0; index < this._children.length; index++) {
  15378. var item = this._children[index];
  15379. if (!predicate || predicate(item)) {
  15380. results.push(item);
  15381. }
  15382. if (!directDescendantsOnly) {
  15383. item._getDescendants(results, false, predicate);
  15384. }
  15385. }
  15386. };
  15387. /**
  15388. * Will return all nodes that have this node as ascendant
  15389. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15390. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15391. * @return all children nodes of all types
  15392. */
  15393. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15394. var results = new Array();
  15395. this._getDescendants(results, directDescendantsOnly, predicate);
  15396. return results;
  15397. };
  15398. /**
  15399. * Get all child-meshes of this node
  15400. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15401. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15402. * @returns an array of {BABYLON.AbstractMesh}
  15403. */
  15404. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15405. var results = [];
  15406. this._getDescendants(results, directDescendantsOnly, function (node) {
  15407. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15408. });
  15409. return results;
  15410. };
  15411. /**
  15412. * Get all child-transformNodes of this node
  15413. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15414. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15415. * @returns an array of {BABYLON.TransformNode}
  15416. */
  15417. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15418. var results = [];
  15419. this._getDescendants(results, directDescendantsOnly, function (node) {
  15420. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15421. });
  15422. return results;
  15423. };
  15424. /**
  15425. * Get all direct children of this node
  15426. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15427. * @returns an array of {BABYLON.Node}
  15428. */
  15429. Node.prototype.getChildren = function (predicate) {
  15430. return this.getDescendants(true, predicate);
  15431. };
  15432. /** @ignore */
  15433. Node.prototype._setReady = function (state) {
  15434. if (state === this._isReady) {
  15435. return;
  15436. }
  15437. if (!state) {
  15438. this._isReady = false;
  15439. return;
  15440. }
  15441. this._isReady = true;
  15442. if (this.onReady) {
  15443. this.onReady(this);
  15444. }
  15445. };
  15446. /**
  15447. * Get an animation by name
  15448. * @param name defines the name of the animation to look for
  15449. * @returns null if not found else the requested animation
  15450. */
  15451. Node.prototype.getAnimationByName = function (name) {
  15452. for (var i = 0; i < this.animations.length; i++) {
  15453. var animation = this.animations[i];
  15454. if (animation.name === name) {
  15455. return animation;
  15456. }
  15457. }
  15458. return null;
  15459. };
  15460. /**
  15461. * Creates an animation range for this node
  15462. * @param name defines the name of the range
  15463. * @param from defines the starting key
  15464. * @param to defines the end key
  15465. */
  15466. Node.prototype.createAnimationRange = function (name, from, to) {
  15467. // check name not already in use
  15468. if (!this._ranges[name]) {
  15469. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15470. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15471. if (this.animations[i]) {
  15472. this.animations[i].createRange(name, from, to);
  15473. }
  15474. }
  15475. }
  15476. };
  15477. /**
  15478. * Delete a specific animation range
  15479. * @param name defines the name of the range to delete
  15480. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15481. */
  15482. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15483. if (deleteFrames === void 0) { deleteFrames = true; }
  15484. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15485. if (this.animations[i]) {
  15486. this.animations[i].deleteRange(name, deleteFrames);
  15487. }
  15488. }
  15489. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15490. };
  15491. /**
  15492. * Get an animation range by name
  15493. * @param name defines the name of the animation range to look for
  15494. * @returns null if not found else the requested animation range
  15495. */
  15496. Node.prototype.getAnimationRange = function (name) {
  15497. return this._ranges[name];
  15498. };
  15499. /**
  15500. * Will start the animation sequence
  15501. * @param name defines the range frames for animation sequence
  15502. * @param loop defines if the animation should loop (false by default)
  15503. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15504. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15505. * @returns the object created for this animation. If range does not exist, it will return null
  15506. */
  15507. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15508. var range = this.getAnimationRange(name);
  15509. if (!range) {
  15510. return null;
  15511. }
  15512. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15513. };
  15514. /**
  15515. * Serialize animation ranges into a JSON compatible object
  15516. * @returns serialization object
  15517. */
  15518. Node.prototype.serializeAnimationRanges = function () {
  15519. var serializationRanges = [];
  15520. for (var name in this._ranges) {
  15521. var localRange = this._ranges[name];
  15522. if (!localRange) {
  15523. continue;
  15524. }
  15525. var range = {};
  15526. range.name = name;
  15527. range.from = localRange.from;
  15528. range.to = localRange.to;
  15529. serializationRanges.push(range);
  15530. }
  15531. return serializationRanges;
  15532. };
  15533. /**
  15534. * Computes the world matrix of the node
  15535. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15536. * @returns the world matrix
  15537. */
  15538. Node.prototype.computeWorldMatrix = function (force) {
  15539. return BABYLON.Matrix.Identity();
  15540. };
  15541. /**
  15542. * Releases all associated resources
  15543. */
  15544. Node.prototype.dispose = function () {
  15545. this.parent = null;
  15546. // Callback
  15547. this.onDisposeObservable.notifyObservers(this);
  15548. this.onDisposeObservable.clear();
  15549. // Behaviors
  15550. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15551. var behavior = _a[_i];
  15552. behavior.detach();
  15553. }
  15554. this._behaviors = [];
  15555. this._isDisposed = true;
  15556. };
  15557. /**
  15558. * Parse animation range data from a serialization object and store them into a given node
  15559. * @param node defines where to store the animation ranges
  15560. * @param parsedNode defines the serialization object to read data from
  15561. * @param scene defines the hosting scene
  15562. */
  15563. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15564. if (parsedNode.ranges) {
  15565. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15566. var data = parsedNode.ranges[index];
  15567. node.createAnimationRange(data.name, data.from, data.to);
  15568. }
  15569. }
  15570. };
  15571. __decorate([
  15572. BABYLON.serialize()
  15573. ], Node.prototype, "name", void 0);
  15574. __decorate([
  15575. BABYLON.serialize()
  15576. ], Node.prototype, "id", void 0);
  15577. __decorate([
  15578. BABYLON.serialize()
  15579. ], Node.prototype, "uniqueId", void 0);
  15580. __decorate([
  15581. BABYLON.serialize()
  15582. ], Node.prototype, "state", void 0);
  15583. __decorate([
  15584. BABYLON.serialize()
  15585. ], Node.prototype, "metadata", void 0);
  15586. return Node;
  15587. }());
  15588. BABYLON.Node = Node;
  15589. })(BABYLON || (BABYLON = {}));
  15590. //# sourceMappingURL=babylon.node.js.map
  15591. var BABYLON;
  15592. (function (BABYLON) {
  15593. var BoundingSphere = /** @class */ (function () {
  15594. function BoundingSphere(minimum, maximum) {
  15595. this.minimum = minimum;
  15596. this.maximum = maximum;
  15597. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15598. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15599. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15600. this.radius = distance * 0.5;
  15601. this.centerWorld = BABYLON.Vector3.Zero();
  15602. this._update(BABYLON.Matrix.Identity());
  15603. }
  15604. // Methods
  15605. BoundingSphere.prototype._update = function (world) {
  15606. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15607. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15608. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15609. };
  15610. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15611. for (var i = 0; i < 6; i++) {
  15612. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15613. return false;
  15614. }
  15615. return true;
  15616. };
  15617. BoundingSphere.prototype.intersectsPoint = function (point) {
  15618. var x = this.centerWorld.x - point.x;
  15619. var y = this.centerWorld.y - point.y;
  15620. var z = this.centerWorld.z - point.z;
  15621. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15622. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15623. return false;
  15624. return true;
  15625. };
  15626. // Statics
  15627. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15628. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15629. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15630. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15631. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15632. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15633. return false;
  15634. return true;
  15635. };
  15636. return BoundingSphere;
  15637. }());
  15638. BABYLON.BoundingSphere = BoundingSphere;
  15639. })(BABYLON || (BABYLON = {}));
  15640. //# sourceMappingURL=babylon.boundingSphere.js.map
  15641. var BABYLON;
  15642. (function (BABYLON) {
  15643. var BoundingBox = /** @class */ (function () {
  15644. function BoundingBox(minimum, maximum) {
  15645. this.minimum = minimum;
  15646. this.maximum = maximum;
  15647. this.vectors = new Array();
  15648. this.vectorsWorld = new Array();
  15649. // Bounding vectors
  15650. this.vectors.push(this.minimum.clone());
  15651. this.vectors.push(this.maximum.clone());
  15652. this.vectors.push(this.minimum.clone());
  15653. this.vectors[2].x = this.maximum.x;
  15654. this.vectors.push(this.minimum.clone());
  15655. this.vectors[3].y = this.maximum.y;
  15656. this.vectors.push(this.minimum.clone());
  15657. this.vectors[4].z = this.maximum.z;
  15658. this.vectors.push(this.maximum.clone());
  15659. this.vectors[5].z = this.minimum.z;
  15660. this.vectors.push(this.maximum.clone());
  15661. this.vectors[6].x = this.minimum.x;
  15662. this.vectors.push(this.maximum.clone());
  15663. this.vectors[7].y = this.minimum.y;
  15664. // OBB
  15665. this.center = this.maximum.add(this.minimum).scale(0.5);
  15666. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15667. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15668. // World
  15669. for (var index = 0; index < this.vectors.length; index++) {
  15670. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15671. }
  15672. this.minimumWorld = BABYLON.Vector3.Zero();
  15673. this.maximumWorld = BABYLON.Vector3.Zero();
  15674. this.centerWorld = BABYLON.Vector3.Zero();
  15675. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15676. this._update(BABYLON.Matrix.Identity());
  15677. }
  15678. // Methods
  15679. BoundingBox.prototype.getWorldMatrix = function () {
  15680. return this._worldMatrix;
  15681. };
  15682. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15683. this._worldMatrix.copyFrom(matrix);
  15684. return this;
  15685. };
  15686. BoundingBox.prototype._update = function (world) {
  15687. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15688. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15689. for (var index = 0; index < this.vectors.length; index++) {
  15690. var v = this.vectorsWorld[index];
  15691. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15692. if (v.x < this.minimumWorld.x)
  15693. this.minimumWorld.x = v.x;
  15694. if (v.y < this.minimumWorld.y)
  15695. this.minimumWorld.y = v.y;
  15696. if (v.z < this.minimumWorld.z)
  15697. this.minimumWorld.z = v.z;
  15698. if (v.x > this.maximumWorld.x)
  15699. this.maximumWorld.x = v.x;
  15700. if (v.y > this.maximumWorld.y)
  15701. this.maximumWorld.y = v.y;
  15702. if (v.z > this.maximumWorld.z)
  15703. this.maximumWorld.z = v.z;
  15704. }
  15705. // Extend
  15706. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15707. this.extendSizeWorld.scaleInPlace(0.5);
  15708. // OBB
  15709. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15710. this.centerWorld.scaleInPlace(0.5);
  15711. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15712. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15713. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15714. this._worldMatrix = world;
  15715. };
  15716. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15717. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15718. };
  15719. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15720. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15721. };
  15722. BoundingBox.prototype.intersectsPoint = function (point) {
  15723. var delta = -BABYLON.Epsilon;
  15724. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15725. return false;
  15726. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15727. return false;
  15728. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15729. return false;
  15730. return true;
  15731. };
  15732. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15733. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15734. };
  15735. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15736. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15737. return false;
  15738. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15739. return false;
  15740. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15741. return false;
  15742. return true;
  15743. };
  15744. // Statics
  15745. BoundingBox.Intersects = function (box0, box1) {
  15746. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  15747. return false;
  15748. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  15749. return false;
  15750. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  15751. return false;
  15752. return true;
  15753. };
  15754. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  15755. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  15756. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  15757. return (num <= (sphereRadius * sphereRadius));
  15758. };
  15759. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  15760. for (var p = 0; p < 6; p++) {
  15761. for (var i = 0; i < 8; i++) {
  15762. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15763. return false;
  15764. }
  15765. }
  15766. }
  15767. return true;
  15768. };
  15769. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  15770. for (var p = 0; p < 6; p++) {
  15771. var inCount = 8;
  15772. for (var i = 0; i < 8; i++) {
  15773. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15774. --inCount;
  15775. }
  15776. else {
  15777. break;
  15778. }
  15779. }
  15780. if (inCount === 0)
  15781. return false;
  15782. }
  15783. return true;
  15784. };
  15785. return BoundingBox;
  15786. }());
  15787. BABYLON.BoundingBox = BoundingBox;
  15788. })(BABYLON || (BABYLON = {}));
  15789. //# sourceMappingURL=babylon.boundingBox.js.map
  15790. var BABYLON;
  15791. (function (BABYLON) {
  15792. var computeBoxExtents = function (axis, box) {
  15793. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  15794. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  15795. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  15796. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  15797. var r = r0 + r1 + r2;
  15798. return {
  15799. min: p - r,
  15800. max: p + r
  15801. };
  15802. };
  15803. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  15804. var axisOverlap = function (axis, box0, box1) {
  15805. var result0 = computeBoxExtents(axis, box0);
  15806. var result1 = computeBoxExtents(axis, box1);
  15807. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  15808. };
  15809. var BoundingInfo = /** @class */ (function () {
  15810. function BoundingInfo(minimum, maximum) {
  15811. this.minimum = minimum;
  15812. this.maximum = maximum;
  15813. this._isLocked = false;
  15814. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  15815. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  15816. }
  15817. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  15818. get: function () {
  15819. return this._isLocked;
  15820. },
  15821. set: function (value) {
  15822. this._isLocked = value;
  15823. },
  15824. enumerable: true,
  15825. configurable: true
  15826. });
  15827. // Methods
  15828. BoundingInfo.prototype.update = function (world) {
  15829. if (this._isLocked) {
  15830. return;
  15831. }
  15832. this.boundingBox._update(world);
  15833. this.boundingSphere._update(world);
  15834. };
  15835. /**
  15836. * Recreate the bounding info to be centered around a specific point given a specific extend.
  15837. * @param center New center of the bounding info
  15838. * @param extend New extend of the bounding info
  15839. */
  15840. BoundingInfo.prototype.centerOn = function (center, extend) {
  15841. this.minimum = center.subtract(extend);
  15842. this.maximum = center.add(extend);
  15843. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  15844. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  15845. return this;
  15846. };
  15847. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  15848. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  15849. return false;
  15850. return this.boundingBox.isInFrustum(frustumPlanes);
  15851. };
  15852. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  15853. /**
  15854. * Gets the world distance between the min and max points of the bounding box
  15855. */
  15856. get: function () {
  15857. var boundingBox = this.boundingBox;
  15858. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  15859. return size.length();
  15860. },
  15861. enumerable: true,
  15862. configurable: true
  15863. });
  15864. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15865. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  15866. };
  15867. BoundingInfo.prototype._checkCollision = function (collider) {
  15868. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  15869. };
  15870. BoundingInfo.prototype.intersectsPoint = function (point) {
  15871. if (!this.boundingSphere.centerWorld) {
  15872. return false;
  15873. }
  15874. if (!this.boundingSphere.intersectsPoint(point)) {
  15875. return false;
  15876. }
  15877. if (!this.boundingBox.intersectsPoint(point)) {
  15878. return false;
  15879. }
  15880. return true;
  15881. };
  15882. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  15883. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  15884. return false;
  15885. }
  15886. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  15887. return false;
  15888. }
  15889. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  15890. return false;
  15891. }
  15892. if (!precise) {
  15893. return true;
  15894. }
  15895. var box0 = this.boundingBox;
  15896. var box1 = boundingInfo.boundingBox;
  15897. if (!axisOverlap(box0.directions[0], box0, box1))
  15898. return false;
  15899. if (!axisOverlap(box0.directions[1], box0, box1))
  15900. return false;
  15901. if (!axisOverlap(box0.directions[2], box0, box1))
  15902. return false;
  15903. if (!axisOverlap(box1.directions[0], box0, box1))
  15904. return false;
  15905. if (!axisOverlap(box1.directions[1], box0, box1))
  15906. return false;
  15907. if (!axisOverlap(box1.directions[2], box0, box1))
  15908. return false;
  15909. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15910. return false;
  15911. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15912. return false;
  15913. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15914. return false;
  15915. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15916. return false;
  15917. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15918. return false;
  15919. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15920. return false;
  15921. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15922. return false;
  15923. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15924. return false;
  15925. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15926. return false;
  15927. return true;
  15928. };
  15929. return BoundingInfo;
  15930. }());
  15931. BABYLON.BoundingInfo = BoundingInfo;
  15932. })(BABYLON || (BABYLON = {}));
  15933. //# sourceMappingURL=babylon.boundingInfo.js.map
  15934. var BABYLON;
  15935. (function (BABYLON) {
  15936. var TransformNode = /** @class */ (function (_super) {
  15937. __extends(TransformNode, _super);
  15938. function TransformNode(name, scene, isPure) {
  15939. if (scene === void 0) { scene = null; }
  15940. if (isPure === void 0) { isPure = true; }
  15941. var _this = _super.call(this, name, scene) || this;
  15942. // Properties
  15943. _this._rotation = BABYLON.Vector3.Zero();
  15944. _this._scaling = BABYLON.Vector3.One();
  15945. _this._isDirty = false;
  15946. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15947. _this.scalingDeterminant = 1;
  15948. _this.infiniteDistance = false;
  15949. _this.position = BABYLON.Vector3.Zero();
  15950. _this._localWorld = BABYLON.Matrix.Zero();
  15951. _this._worldMatrix = BABYLON.Matrix.Zero();
  15952. _this._worldMatrixDeterminant = 0;
  15953. _this._absolutePosition = BABYLON.Vector3.Zero();
  15954. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15955. _this._postMultiplyPivotMatrix = false;
  15956. _this._isWorldMatrixFrozen = false;
  15957. /**
  15958. * An event triggered after the world matrix is updated
  15959. * @type {BABYLON.Observable}
  15960. */
  15961. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15962. _this._nonUniformScaling = false;
  15963. if (isPure) {
  15964. _this.getScene().addTransformNode(_this);
  15965. }
  15966. return _this;
  15967. }
  15968. Object.defineProperty(TransformNode.prototype, "rotation", {
  15969. /**
  15970. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15971. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15972. * Default : (0.0, 0.0, 0.0)
  15973. */
  15974. get: function () {
  15975. return this._rotation;
  15976. },
  15977. set: function (newRotation) {
  15978. this._rotation = newRotation;
  15979. },
  15980. enumerable: true,
  15981. configurable: true
  15982. });
  15983. Object.defineProperty(TransformNode.prototype, "scaling", {
  15984. /**
  15985. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15986. * Default : (1.0, 1.0, 1.0)
  15987. */
  15988. get: function () {
  15989. return this._scaling;
  15990. },
  15991. /**
  15992. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15993. * Default : (1.0, 1.0, 1.0)
  15994. */
  15995. set: function (newScaling) {
  15996. this._scaling = newScaling;
  15997. },
  15998. enumerable: true,
  15999. configurable: true
  16000. });
  16001. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16002. /**
  16003. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16004. * It's null by default.
  16005. * 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)
  16006. */
  16007. get: function () {
  16008. return this._rotationQuaternion;
  16009. },
  16010. set: function (quaternion) {
  16011. this._rotationQuaternion = quaternion;
  16012. //reset the rotation vector.
  16013. if (quaternion && this.rotation.length()) {
  16014. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16015. }
  16016. },
  16017. enumerable: true,
  16018. configurable: true
  16019. });
  16020. /**
  16021. * Returns the latest update of the World matrix
  16022. * Returns a Matrix.
  16023. */
  16024. TransformNode.prototype.getWorldMatrix = function () {
  16025. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16026. this.computeWorldMatrix();
  16027. }
  16028. return this._worldMatrix;
  16029. };
  16030. /**
  16031. * Returns the latest update of the World matrix determinant.
  16032. */
  16033. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16034. return this._worldMatrixDeterminant;
  16035. };
  16036. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16037. /**
  16038. * Returns directly the latest state of the mesh World matrix.
  16039. * A Matrix is returned.
  16040. */
  16041. get: function () {
  16042. return this._worldMatrix;
  16043. },
  16044. enumerable: true,
  16045. configurable: true
  16046. });
  16047. /**
  16048. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16049. * Returns the AbstractMesh.
  16050. */
  16051. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16052. this._poseMatrix.copyFrom(matrix);
  16053. return this;
  16054. };
  16055. /**
  16056. * Returns the mesh Pose matrix.
  16057. * Returned object : Matrix
  16058. */
  16059. TransformNode.prototype.getPoseMatrix = function () {
  16060. return this._poseMatrix;
  16061. };
  16062. TransformNode.prototype._isSynchronized = function () {
  16063. if (this._isDirty) {
  16064. return false;
  16065. }
  16066. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16067. return false;
  16068. if (this._cache.pivotMatrixUpdated) {
  16069. return false;
  16070. }
  16071. if (this.infiniteDistance) {
  16072. return false;
  16073. }
  16074. if (!this._cache.position.equals(this.position))
  16075. return false;
  16076. if (this.rotationQuaternion) {
  16077. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16078. return false;
  16079. }
  16080. if (!this._cache.rotation.equals(this.rotation))
  16081. return false;
  16082. if (!this._cache.scaling.equals(this.scaling))
  16083. return false;
  16084. return true;
  16085. };
  16086. TransformNode.prototype._initCache = function () {
  16087. _super.prototype._initCache.call(this);
  16088. this._cache.localMatrixUpdated = false;
  16089. this._cache.position = BABYLON.Vector3.Zero();
  16090. this._cache.scaling = BABYLON.Vector3.Zero();
  16091. this._cache.rotation = BABYLON.Vector3.Zero();
  16092. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16093. this._cache.billboardMode = -1;
  16094. };
  16095. TransformNode.prototype.markAsDirty = function (property) {
  16096. if (property === "rotation") {
  16097. this.rotationQuaternion = null;
  16098. }
  16099. this._currentRenderId = Number.MAX_VALUE;
  16100. this._isDirty = true;
  16101. return this;
  16102. };
  16103. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16104. /**
  16105. * Returns the current mesh absolute position.
  16106. * Retuns a Vector3.
  16107. */
  16108. get: function () {
  16109. return this._absolutePosition;
  16110. },
  16111. enumerable: true,
  16112. configurable: true
  16113. });
  16114. /**
  16115. * Sets a new matrix to apply before all other transformation
  16116. * @param matrix defines the transform matrix
  16117. * @returns the current TransformNode
  16118. */
  16119. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16120. return this.setPivotMatrix(matrix, false);
  16121. };
  16122. /**
  16123. * Sets a new pivot matrix to the current node
  16124. * @param matrix defines the new pivot matrix to use
  16125. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  16126. * @returns the current TransformNode
  16127. */
  16128. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16129. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16130. this._pivotMatrix = matrix.clone();
  16131. this._cache.pivotMatrixUpdated = true;
  16132. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16133. if (this._postMultiplyPivotMatrix) {
  16134. if (!this._pivotMatrixInverse) {
  16135. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16136. }
  16137. else {
  16138. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16139. }
  16140. }
  16141. return this;
  16142. };
  16143. /**
  16144. * Returns the mesh pivot matrix.
  16145. * Default : Identity.
  16146. * A Matrix is returned.
  16147. */
  16148. TransformNode.prototype.getPivotMatrix = function () {
  16149. return this._pivotMatrix;
  16150. };
  16151. /**
  16152. * Prevents the World matrix to be computed any longer.
  16153. * Returns the AbstractMesh.
  16154. */
  16155. TransformNode.prototype.freezeWorldMatrix = function () {
  16156. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16157. this.computeWorldMatrix(true);
  16158. this._isWorldMatrixFrozen = true;
  16159. return this;
  16160. };
  16161. /**
  16162. * Allows back the World matrix computation.
  16163. * Returns the AbstractMesh.
  16164. */
  16165. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16166. this._isWorldMatrixFrozen = false;
  16167. this.computeWorldMatrix(true);
  16168. return this;
  16169. };
  16170. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16171. /**
  16172. * True if the World matrix has been frozen.
  16173. * Returns a boolean.
  16174. */
  16175. get: function () {
  16176. return this._isWorldMatrixFrozen;
  16177. },
  16178. enumerable: true,
  16179. configurable: true
  16180. });
  16181. /**
  16182. * Retuns the mesh absolute position in the World.
  16183. * Returns a Vector3.
  16184. */
  16185. TransformNode.prototype.getAbsolutePosition = function () {
  16186. this.computeWorldMatrix();
  16187. return this._absolutePosition;
  16188. };
  16189. /**
  16190. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16191. * Returns the AbstractMesh.
  16192. */
  16193. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16194. if (!absolutePosition) {
  16195. return this;
  16196. }
  16197. var absolutePositionX;
  16198. var absolutePositionY;
  16199. var absolutePositionZ;
  16200. if (absolutePosition.x === undefined) {
  16201. if (arguments.length < 3) {
  16202. return this;
  16203. }
  16204. absolutePositionX = arguments[0];
  16205. absolutePositionY = arguments[1];
  16206. absolutePositionZ = arguments[2];
  16207. }
  16208. else {
  16209. absolutePositionX = absolutePosition.x;
  16210. absolutePositionY = absolutePosition.y;
  16211. absolutePositionZ = absolutePosition.z;
  16212. }
  16213. if (this.parent) {
  16214. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16215. invertParentWorldMatrix.invert();
  16216. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16217. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16218. }
  16219. else {
  16220. this.position.x = absolutePositionX;
  16221. this.position.y = absolutePositionY;
  16222. this.position.z = absolutePositionZ;
  16223. }
  16224. return this;
  16225. };
  16226. /**
  16227. * Sets the mesh position in its local space.
  16228. * Returns the AbstractMesh.
  16229. */
  16230. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16231. this.computeWorldMatrix();
  16232. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16233. return this;
  16234. };
  16235. /**
  16236. * Returns the mesh position in the local space from the current World matrix values.
  16237. * Returns a new Vector3.
  16238. */
  16239. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16240. this.computeWorldMatrix();
  16241. var invLocalWorldMatrix = this._localWorld.clone();
  16242. invLocalWorldMatrix.invert();
  16243. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16244. };
  16245. /**
  16246. * Translates the mesh along the passed Vector3 in its local space.
  16247. * Returns the AbstractMesh.
  16248. */
  16249. TransformNode.prototype.locallyTranslate = function (vector3) {
  16250. this.computeWorldMatrix(true);
  16251. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16252. return this;
  16253. };
  16254. /**
  16255. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16256. * @param targetPoint the position (must be in same space as current mesh) to look at
  16257. * @param yawCor optional yaw (y-axis) correction in radians
  16258. * @param pitchCor optional pitch (x-axis) correction in radians
  16259. * @param rollCor optional roll (z-axis) correction in radians
  16260. * @param space the choosen space of the target
  16261. * @returns the TransformNode.
  16262. */
  16263. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16264. if (yawCor === void 0) { yawCor = 0; }
  16265. if (pitchCor === void 0) { pitchCor = 0; }
  16266. if (rollCor === void 0) { rollCor = 0; }
  16267. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16268. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16269. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16270. targetPoint.subtractToRef(pos, dv);
  16271. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16272. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16273. var pitch = Math.atan2(dv.y, len);
  16274. if (this.rotationQuaternion) {
  16275. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16276. }
  16277. else {
  16278. this.rotation.x = pitch + pitchCor;
  16279. this.rotation.y = yaw + yawCor;
  16280. this.rotation.z = rollCor;
  16281. }
  16282. return this;
  16283. };
  16284. /**
  16285. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16286. * This Vector3 is expressed in the World space.
  16287. */
  16288. TransformNode.prototype.getDirection = function (localAxis) {
  16289. var result = BABYLON.Vector3.Zero();
  16290. this.getDirectionToRef(localAxis, result);
  16291. return result;
  16292. };
  16293. /**
  16294. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16295. * localAxis is expressed in the mesh local space.
  16296. * result is computed in the Wordl space from the mesh World matrix.
  16297. * Returns the AbstractMesh.
  16298. */
  16299. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16300. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16301. return this;
  16302. };
  16303. /**
  16304. * Sets a new pivot point to the current node
  16305. * @param point defines the new pivot point to use
  16306. * @param space defines if the point is in world or local space (local by default)
  16307. * @returns the current TransformNode
  16308. */
  16309. TransformNode.prototype.setPivotPoint = function (point, space) {
  16310. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16311. if (this.getScene().getRenderId() == 0) {
  16312. this.computeWorldMatrix(true);
  16313. }
  16314. var wm = this.getWorldMatrix();
  16315. if (space == BABYLON.Space.WORLD) {
  16316. var tmat = BABYLON.Tmp.Matrix[0];
  16317. wm.invertToRef(tmat);
  16318. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16319. }
  16320. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16321. };
  16322. /**
  16323. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16324. */
  16325. TransformNode.prototype.getPivotPoint = function () {
  16326. var point = BABYLON.Vector3.Zero();
  16327. this.getPivotPointToRef(point);
  16328. return point;
  16329. };
  16330. /**
  16331. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16332. * Returns the AbstractMesh.
  16333. */
  16334. TransformNode.prototype.getPivotPointToRef = function (result) {
  16335. result.x = -this._pivotMatrix.m[12];
  16336. result.y = -this._pivotMatrix.m[13];
  16337. result.z = -this._pivotMatrix.m[14];
  16338. return this;
  16339. };
  16340. /**
  16341. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16342. */
  16343. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16344. var point = BABYLON.Vector3.Zero();
  16345. this.getAbsolutePivotPointToRef(point);
  16346. return point;
  16347. };
  16348. /**
  16349. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16350. * Returns the AbstractMesh.
  16351. */
  16352. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16353. result.x = this._pivotMatrix.m[12];
  16354. result.y = this._pivotMatrix.m[13];
  16355. result.z = this._pivotMatrix.m[14];
  16356. this.getPivotPointToRef(result);
  16357. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16358. return this;
  16359. };
  16360. /**
  16361. * Defines the passed node as the parent of the current node.
  16362. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16363. * Returns the TransformNode.
  16364. */
  16365. TransformNode.prototype.setParent = function (node) {
  16366. if (node === null) {
  16367. var rotation = BABYLON.Tmp.Quaternion[0];
  16368. var position = BABYLON.Tmp.Vector3[0];
  16369. var scale = BABYLON.Tmp.Vector3[1];
  16370. if (this.parent && this.parent.computeWorldMatrix) {
  16371. this.parent.computeWorldMatrix(true);
  16372. }
  16373. this.computeWorldMatrix(true);
  16374. this.getWorldMatrix().decompose(scale, rotation, position);
  16375. if (this.rotationQuaternion) {
  16376. this.rotationQuaternion.copyFrom(rotation);
  16377. }
  16378. else {
  16379. rotation.toEulerAnglesToRef(this.rotation);
  16380. }
  16381. this.scaling.x = scale.x;
  16382. this.scaling.y = scale.y;
  16383. this.scaling.z = scale.z;
  16384. this.position.x = position.x;
  16385. this.position.y = position.y;
  16386. this.position.z = position.z;
  16387. }
  16388. else {
  16389. var rotation = BABYLON.Tmp.Quaternion[0];
  16390. var position = BABYLON.Tmp.Vector3[0];
  16391. var scale = BABYLON.Tmp.Vector3[1];
  16392. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16393. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16394. this.computeWorldMatrix(true);
  16395. node.computeWorldMatrix(true);
  16396. node.getWorldMatrix().invertToRef(invParentMatrix);
  16397. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16398. diffMatrix.decompose(scale, rotation, position);
  16399. if (this.rotationQuaternion) {
  16400. this.rotationQuaternion.copyFrom(rotation);
  16401. }
  16402. else {
  16403. rotation.toEulerAnglesToRef(this.rotation);
  16404. }
  16405. this.position.x = position.x;
  16406. this.position.y = position.y;
  16407. this.position.z = position.z;
  16408. this.scaling.x = scale.x;
  16409. this.scaling.y = scale.y;
  16410. this.scaling.z = scale.z;
  16411. }
  16412. this.parent = node;
  16413. return this;
  16414. };
  16415. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16416. get: function () {
  16417. return this._nonUniformScaling;
  16418. },
  16419. enumerable: true,
  16420. configurable: true
  16421. });
  16422. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16423. if (this._nonUniformScaling === value) {
  16424. return false;
  16425. }
  16426. this._nonUniformScaling = true;
  16427. return true;
  16428. };
  16429. /**
  16430. * Attach the current TransformNode to another TransformNode associated with a bone
  16431. * @param bone Bone affecting the TransformNode
  16432. * @param affectedTransformNode TransformNode associated with the bone
  16433. */
  16434. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16435. this._transformToBoneReferal = affectedTransformNode;
  16436. this.parent = bone;
  16437. if (bone.getWorldMatrix().determinant() < 0) {
  16438. this.scalingDeterminant *= -1;
  16439. }
  16440. return this;
  16441. };
  16442. TransformNode.prototype.detachFromBone = function () {
  16443. if (!this.parent) {
  16444. return this;
  16445. }
  16446. if (this.parent.getWorldMatrix().determinant() < 0) {
  16447. this.scalingDeterminant *= -1;
  16448. }
  16449. this._transformToBoneReferal = null;
  16450. this.parent = null;
  16451. return this;
  16452. };
  16453. /**
  16454. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16455. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16456. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16457. * The passed axis is also normalized.
  16458. * Returns the AbstractMesh.
  16459. */
  16460. TransformNode.prototype.rotate = function (axis, amount, space) {
  16461. axis.normalize();
  16462. if (!this.rotationQuaternion) {
  16463. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16464. this.rotation = BABYLON.Vector3.Zero();
  16465. }
  16466. var rotationQuaternion;
  16467. if (!space || space === BABYLON.Space.LOCAL) {
  16468. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16469. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16470. }
  16471. else {
  16472. if (this.parent) {
  16473. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16474. invertParentWorldMatrix.invert();
  16475. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16476. }
  16477. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16478. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16479. }
  16480. return this;
  16481. };
  16482. /**
  16483. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16484. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16485. * The passed axis is also normalized.
  16486. * Returns the AbstractMesh.
  16487. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16488. */
  16489. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16490. axis.normalize();
  16491. if (!this.rotationQuaternion) {
  16492. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16493. this.rotation.copyFromFloats(0, 0, 0);
  16494. }
  16495. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16496. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16497. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16498. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16499. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16500. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16501. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16502. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16503. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16504. return this;
  16505. };
  16506. /**
  16507. * Translates the mesh along the axis vector for the passed distance in the given space.
  16508. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16509. * Returns the AbstractMesh.
  16510. */
  16511. TransformNode.prototype.translate = function (axis, distance, space) {
  16512. var displacementVector = axis.scale(distance);
  16513. if (!space || space === BABYLON.Space.LOCAL) {
  16514. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16515. this.setPositionWithLocalVector(tempV3);
  16516. }
  16517. else {
  16518. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16519. }
  16520. return this;
  16521. };
  16522. /**
  16523. * Adds a rotation step to the mesh current rotation.
  16524. * x, y, z are Euler angles expressed in radians.
  16525. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16526. * This means this rotation is made in the mesh local space only.
  16527. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16528. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16529. * ```javascript
  16530. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16531. * ```
  16532. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16533. * 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.
  16534. * Returns the AbstractMesh.
  16535. */
  16536. TransformNode.prototype.addRotation = function (x, y, z) {
  16537. var rotationQuaternion;
  16538. if (this.rotationQuaternion) {
  16539. rotationQuaternion = this.rotationQuaternion;
  16540. }
  16541. else {
  16542. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16543. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16544. }
  16545. var accumulation = BABYLON.Tmp.Quaternion[0];
  16546. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16547. rotationQuaternion.multiplyInPlace(accumulation);
  16548. if (!this.rotationQuaternion) {
  16549. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16550. }
  16551. return this;
  16552. };
  16553. /**
  16554. * Computes the mesh World matrix and returns it.
  16555. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16556. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16557. * If the parameter `force`is set to `true`, the actual computation is done.
  16558. * Returns the mesh World Matrix.
  16559. */
  16560. TransformNode.prototype.computeWorldMatrix = function (force) {
  16561. if (this._isWorldMatrixFrozen) {
  16562. return this._worldMatrix;
  16563. }
  16564. if (!force && this.isSynchronized(true)) {
  16565. return this._worldMatrix;
  16566. }
  16567. this._cache.position.copyFrom(this.position);
  16568. this._cache.scaling.copyFrom(this.scaling);
  16569. this._cache.pivotMatrixUpdated = false;
  16570. this._cache.billboardMode = this.billboardMode;
  16571. this._currentRenderId = this.getScene().getRenderId();
  16572. this._isDirty = false;
  16573. // Scaling
  16574. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16575. // Rotation
  16576. //rotate, if quaternion is set and rotation was used
  16577. if (this.rotationQuaternion) {
  16578. var len = this.rotation.length();
  16579. if (len) {
  16580. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16581. this.rotation.copyFromFloats(0, 0, 0);
  16582. }
  16583. }
  16584. if (this.rotationQuaternion) {
  16585. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16586. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16587. }
  16588. else {
  16589. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16590. this._cache.rotation.copyFrom(this.rotation);
  16591. }
  16592. // Translation
  16593. var camera = this.getScene().activeCamera;
  16594. if (this.infiniteDistance && !this.parent && camera) {
  16595. var cameraWorldMatrix = camera.getWorldMatrix();
  16596. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16597. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16598. }
  16599. else {
  16600. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16601. }
  16602. // Composing transformations
  16603. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16604. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16605. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16606. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16607. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16608. // Need to decompose each rotation here
  16609. var currentPosition = BABYLON.Tmp.Vector3[3];
  16610. if (this.parent && this.parent.getWorldMatrix) {
  16611. if (this._transformToBoneReferal) {
  16612. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16613. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16614. }
  16615. else {
  16616. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16617. }
  16618. }
  16619. else {
  16620. currentPosition.copyFrom(this.position);
  16621. }
  16622. currentPosition.subtractInPlace(camera.globalPosition);
  16623. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16624. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16625. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16626. }
  16627. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16628. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16629. }
  16630. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16631. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16632. }
  16633. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16634. }
  16635. else {
  16636. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16637. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16638. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16639. }
  16640. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16641. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16642. }
  16643. // Local world
  16644. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16645. // Parent
  16646. if (this.parent && this.parent.getWorldMatrix) {
  16647. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16648. if (this._transformToBoneReferal) {
  16649. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16650. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16651. }
  16652. else {
  16653. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16654. }
  16655. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16656. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16657. this._worldMatrix.copyFrom(this._localWorld);
  16658. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16659. }
  16660. else {
  16661. if (this._transformToBoneReferal) {
  16662. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16663. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16664. }
  16665. else {
  16666. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16667. }
  16668. }
  16669. this._markSyncedWithParent();
  16670. }
  16671. else {
  16672. this._worldMatrix.copyFrom(this._localWorld);
  16673. }
  16674. // Post multiply inverse of pivotMatrix
  16675. if (this._postMultiplyPivotMatrix) {
  16676. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16677. }
  16678. // Normal matrix
  16679. if (this.scaling.isNonUniform) {
  16680. this._updateNonUniformScalingState(true);
  16681. }
  16682. else if (this.parent && this.parent._nonUniformScaling) {
  16683. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16684. }
  16685. else {
  16686. this._updateNonUniformScalingState(false);
  16687. }
  16688. this._afterComputeWorldMatrix();
  16689. // Absolute position
  16690. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16691. // Callbacks
  16692. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16693. if (!this._poseMatrix) {
  16694. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16695. }
  16696. // Cache the determinant
  16697. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16698. return this._worldMatrix;
  16699. };
  16700. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16701. };
  16702. /**
  16703. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16704. * @param func: callback function to add
  16705. *
  16706. * Returns the TransformNode.
  16707. */
  16708. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16709. this.onAfterWorldMatrixUpdateObservable.add(func);
  16710. return this;
  16711. };
  16712. /**
  16713. * Removes a registered callback function.
  16714. * Returns the TransformNode.
  16715. */
  16716. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16717. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16718. return this;
  16719. };
  16720. /**
  16721. * Clone the current transform node
  16722. * Returns the new transform node
  16723. * @param name Name of the new clone
  16724. * @param newParent New parent for the clone
  16725. * @param doNotCloneChildren Do not clone children hierarchy
  16726. */
  16727. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16728. var _this = this;
  16729. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16730. result.name = name;
  16731. result.id = name;
  16732. if (newParent) {
  16733. result.parent = newParent;
  16734. }
  16735. if (!doNotCloneChildren) {
  16736. // Children
  16737. var directDescendants = this.getDescendants(true);
  16738. for (var index = 0; index < directDescendants.length; index++) {
  16739. var child = directDescendants[index];
  16740. if (child.clone) {
  16741. child.clone(name + "." + child.name, result);
  16742. }
  16743. }
  16744. }
  16745. return result;
  16746. };
  16747. TransformNode.prototype.serialize = function (currentSerializationObject) {
  16748. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  16749. serializationObject.type = this.getClassName();
  16750. // Parent
  16751. if (this.parent) {
  16752. serializationObject.parentId = this.parent.id;
  16753. }
  16754. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  16755. serializationObject.tags = BABYLON.Tags.GetTags(this);
  16756. }
  16757. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  16758. serializationObject.isEnabled = this.isEnabled();
  16759. // Parent
  16760. if (this.parent) {
  16761. serializationObject.parentId = this.parent.id;
  16762. }
  16763. return serializationObject;
  16764. };
  16765. // Statics
  16766. /**
  16767. * Returns a new TransformNode object parsed from the source provided.
  16768. * The parameter `parsedMesh` is the source.
  16769. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  16770. */
  16771. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  16772. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  16773. if (BABYLON.Tags) {
  16774. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  16775. }
  16776. if (parsedTransformNode.localMatrix) {
  16777. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  16778. }
  16779. else if (parsedTransformNode.pivotMatrix) {
  16780. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  16781. }
  16782. transformNode.setEnabled(parsedTransformNode.isEnabled);
  16783. // Parent
  16784. if (parsedTransformNode.parentId) {
  16785. transformNode._waitingParentId = parsedTransformNode.parentId;
  16786. }
  16787. return transformNode;
  16788. };
  16789. /**
  16790. * Disposes the TransformNode.
  16791. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16792. * Returns nothing.
  16793. */
  16794. TransformNode.prototype.dispose = function (doNotRecurse) {
  16795. // Animations
  16796. this.getScene().stopAnimation(this);
  16797. // Remove from scene
  16798. this.getScene().removeTransformNode(this);
  16799. if (!doNotRecurse) {
  16800. // Children
  16801. var objects = this.getDescendants(true);
  16802. for (var index = 0; index < objects.length; index++) {
  16803. objects[index].dispose();
  16804. }
  16805. }
  16806. else {
  16807. var childMeshes = this.getChildMeshes(true);
  16808. for (index = 0; index < childMeshes.length; index++) {
  16809. var child = childMeshes[index];
  16810. child.parent = null;
  16811. child.computeWorldMatrix(true);
  16812. }
  16813. }
  16814. this.onAfterWorldMatrixUpdateObservable.clear();
  16815. _super.prototype.dispose.call(this);
  16816. };
  16817. // Statics
  16818. TransformNode.BILLBOARDMODE_NONE = 0;
  16819. TransformNode.BILLBOARDMODE_X = 1;
  16820. TransformNode.BILLBOARDMODE_Y = 2;
  16821. TransformNode.BILLBOARDMODE_Z = 4;
  16822. TransformNode.BILLBOARDMODE_ALL = 7;
  16823. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  16824. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  16825. __decorate([
  16826. BABYLON.serializeAsVector3()
  16827. ], TransformNode.prototype, "_rotation", void 0);
  16828. __decorate([
  16829. BABYLON.serializeAsQuaternion()
  16830. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  16831. __decorate([
  16832. BABYLON.serializeAsVector3()
  16833. ], TransformNode.prototype, "_scaling", void 0);
  16834. __decorate([
  16835. BABYLON.serialize()
  16836. ], TransformNode.prototype, "billboardMode", void 0);
  16837. __decorate([
  16838. BABYLON.serialize()
  16839. ], TransformNode.prototype, "scalingDeterminant", void 0);
  16840. __decorate([
  16841. BABYLON.serialize()
  16842. ], TransformNode.prototype, "infiniteDistance", void 0);
  16843. __decorate([
  16844. BABYLON.serializeAsVector3()
  16845. ], TransformNode.prototype, "position", void 0);
  16846. return TransformNode;
  16847. }(BABYLON.Node));
  16848. BABYLON.TransformNode = TransformNode;
  16849. })(BABYLON || (BABYLON = {}));
  16850. //# sourceMappingURL=babylon.transformNode.js.map
  16851. var BABYLON;
  16852. (function (BABYLON) {
  16853. var AbstractMesh = /** @class */ (function (_super) {
  16854. __extends(AbstractMesh, _super);
  16855. // Constructor
  16856. function AbstractMesh(name, scene) {
  16857. if (scene === void 0) { scene = null; }
  16858. var _this = _super.call(this, name, scene, false) || this;
  16859. _this._facetNb = 0; // facet number
  16860. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  16861. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  16862. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  16863. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  16864. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  16865. _this._subDiv = {
  16866. max: 1,
  16867. X: 1,
  16868. Y: 1,
  16869. Z: 1
  16870. };
  16871. _this._facetDepthSort = false; // is the facet depth sort to be computed
  16872. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  16873. // Events
  16874. /**
  16875. * An event triggered when this mesh collides with another one
  16876. * @type {BABYLON.Observable}
  16877. */
  16878. _this.onCollideObservable = new BABYLON.Observable();
  16879. /**
  16880. * An event triggered when the collision's position changes
  16881. * @type {BABYLON.Observable}
  16882. */
  16883. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  16884. /**
  16885. * An event triggered when material is changed
  16886. * @type {BABYLON.Observable}
  16887. */
  16888. _this.onMaterialChangedObservable = new BABYLON.Observable();
  16889. // Properties
  16890. _this.definedFacingForward = true; // orientation for POV movement & rotation
  16891. /**
  16892. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  16893. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  16894. * or
  16895. * 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.
  16896. * for more info check WebGl documentations
  16897. */
  16898. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  16899. /**
  16900. * 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:
  16901. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  16902. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  16903. * 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.
  16904. */
  16905. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  16906. /**
  16907. * 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.
  16908. * The default value is -1 which means don't break the query and wait till the result.
  16909. */
  16910. _this.occlusionRetryCount = -1;
  16911. _this._occlusionInternalRetryCounter = 0;
  16912. _this._isOccluded = false;
  16913. _this._isOcclusionQueryInProgress = false;
  16914. _this._visibility = 1.0;
  16915. _this.alphaIndex = Number.MAX_VALUE;
  16916. _this.isVisible = true;
  16917. _this.isPickable = true;
  16918. _this.showBoundingBox = false;
  16919. _this.showSubMeshesBoundingBox = false;
  16920. _this.isBlocker = false;
  16921. _this.enablePointerMoveEvents = false;
  16922. _this.renderingGroupId = 0;
  16923. _this._receiveShadows = false;
  16924. _this.renderOutline = false;
  16925. _this.outlineColor = BABYLON.Color3.Red();
  16926. _this.outlineWidth = 0.02;
  16927. _this.renderOverlay = false;
  16928. _this.overlayColor = BABYLON.Color3.Red();
  16929. _this.overlayAlpha = 0.5;
  16930. _this._hasVertexAlpha = false;
  16931. _this._useVertexColors = true;
  16932. _this._computeBonesUsingShaders = true;
  16933. _this._numBoneInfluencers = 4;
  16934. _this._applyFog = true;
  16935. _this.useOctreeForRenderingSelection = true;
  16936. _this.useOctreeForPicking = true;
  16937. _this.useOctreeForCollisions = true;
  16938. _this._layerMask = 0x0FFFFFFF;
  16939. /**
  16940. * True if the mesh must be rendered in any case.
  16941. */
  16942. _this.alwaysSelectAsActiveMesh = false;
  16943. /**
  16944. * This scene's action manager
  16945. * @type {BABYLON.ActionManager}
  16946. */
  16947. _this.actionManager = null;
  16948. // Physics
  16949. _this.physicsImpostor = null;
  16950. // Collisions
  16951. _this._checkCollisions = false;
  16952. _this._collisionMask = -1;
  16953. _this._collisionGroup = -1;
  16954. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16955. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16956. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16957. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16958. // Edges
  16959. _this.edgesWidth = 1;
  16960. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16961. // Cache
  16962. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16963. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16964. _this._renderId = 0;
  16965. _this._intersectionsInProgress = new Array();
  16966. _this._unIndexed = false;
  16967. _this._lightSources = new Array();
  16968. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16969. if (collidedMesh === void 0) { collidedMesh = null; }
  16970. //TODO move this to the collision coordinator!
  16971. if (_this.getScene().workerCollisions)
  16972. newPosition.multiplyInPlace(_this._collider._radius);
  16973. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16974. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16975. _this.position.addInPlace(_this._diffPositionForCollisions);
  16976. }
  16977. if (collidedMesh) {
  16978. _this.onCollideObservable.notifyObservers(collidedMesh);
  16979. }
  16980. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16981. };
  16982. _this.getScene().addMesh(_this);
  16983. _this._resyncLightSources();
  16984. return _this;
  16985. }
  16986. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16987. get: function () {
  16988. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16989. },
  16990. enumerable: true,
  16991. configurable: true
  16992. });
  16993. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16994. get: function () {
  16995. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16996. },
  16997. enumerable: true,
  16998. configurable: true
  16999. });
  17000. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17001. get: function () {
  17002. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17003. },
  17004. enumerable: true,
  17005. configurable: true
  17006. });
  17007. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17008. get: function () {
  17009. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17010. },
  17011. enumerable: true,
  17012. configurable: true
  17013. });
  17014. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17015. get: function () {
  17016. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17017. },
  17018. enumerable: true,
  17019. configurable: true
  17020. });
  17021. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17022. /**
  17023. * Read-only : the number of facets in the mesh
  17024. */
  17025. get: function () {
  17026. return this._facetNb;
  17027. },
  17028. enumerable: true,
  17029. configurable: true
  17030. });
  17031. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17032. /**
  17033. * The number (integer) of subdivisions per axis in the partioning space
  17034. */
  17035. get: function () {
  17036. return this._partitioningSubdivisions;
  17037. },
  17038. set: function (nb) {
  17039. this._partitioningSubdivisions = nb;
  17040. },
  17041. enumerable: true,
  17042. configurable: true
  17043. });
  17044. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17045. /**
  17046. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17047. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17048. */
  17049. get: function () {
  17050. return this._partitioningBBoxRatio;
  17051. },
  17052. set: function (ratio) {
  17053. this._partitioningBBoxRatio = ratio;
  17054. },
  17055. enumerable: true,
  17056. configurable: true
  17057. });
  17058. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17059. /**
  17060. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17061. * Works only for updatable meshes.
  17062. * Doesn't work with multi-materials.
  17063. */
  17064. get: function () {
  17065. return this._facetDepthSort;
  17066. },
  17067. set: function (sort) {
  17068. this._facetDepthSort = sort;
  17069. },
  17070. enumerable: true,
  17071. configurable: true
  17072. });
  17073. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17074. /**
  17075. * The location (Vector3) where the facet depth sort must be computed from.
  17076. * By default, the active camera position.
  17077. * Used only when facet depth sort is enabled.
  17078. */
  17079. get: function () {
  17080. return this._facetDepthSortFrom;
  17081. },
  17082. set: function (location) {
  17083. this._facetDepthSortFrom = location;
  17084. },
  17085. enumerable: true,
  17086. configurable: true
  17087. });
  17088. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17089. /**
  17090. * Read-only boolean : is the feature facetData enabled ?
  17091. */
  17092. get: function () {
  17093. return this._facetDataEnabled;
  17094. },
  17095. enumerable: true,
  17096. configurable: true
  17097. });
  17098. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17099. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17100. return false;
  17101. }
  17102. this._markSubMeshesAsMiscDirty();
  17103. return true;
  17104. };
  17105. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17106. set: function (callback) {
  17107. if (this._onCollideObserver) {
  17108. this.onCollideObservable.remove(this._onCollideObserver);
  17109. }
  17110. this._onCollideObserver = this.onCollideObservable.add(callback);
  17111. },
  17112. enumerable: true,
  17113. configurable: true
  17114. });
  17115. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17116. set: function (callback) {
  17117. if (this._onCollisionPositionChangeObserver) {
  17118. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17119. }
  17120. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17121. },
  17122. enumerable: true,
  17123. configurable: true
  17124. });
  17125. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17126. /**
  17127. * 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.
  17128. */
  17129. get: function () {
  17130. return this._isOccluded;
  17131. },
  17132. set: function (value) {
  17133. this._isOccluded = value;
  17134. },
  17135. enumerable: true,
  17136. configurable: true
  17137. });
  17138. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17139. /**
  17140. * Flag to check the progress status of the query
  17141. */
  17142. get: function () {
  17143. return this._isOcclusionQueryInProgress;
  17144. },
  17145. enumerable: true,
  17146. configurable: true
  17147. });
  17148. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17149. /**
  17150. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17151. */
  17152. get: function () {
  17153. return this._visibility;
  17154. },
  17155. /**
  17156. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17157. */
  17158. set: function (value) {
  17159. if (this._visibility === value) {
  17160. return;
  17161. }
  17162. this._visibility = value;
  17163. this._markSubMeshesAsMiscDirty();
  17164. },
  17165. enumerable: true,
  17166. configurable: true
  17167. });
  17168. Object.defineProperty(AbstractMesh.prototype, "material", {
  17169. get: function () {
  17170. return this._material;
  17171. },
  17172. set: function (value) {
  17173. if (this._material === value) {
  17174. return;
  17175. }
  17176. this._material = value;
  17177. if (this.onMaterialChangedObservable.hasObservers) {
  17178. this.onMaterialChangedObservable.notifyObservers(this);
  17179. }
  17180. if (!this.subMeshes) {
  17181. return;
  17182. }
  17183. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17184. var subMesh = _a[_i];
  17185. subMesh.setEffect(null);
  17186. }
  17187. },
  17188. enumerable: true,
  17189. configurable: true
  17190. });
  17191. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17192. get: function () {
  17193. return this._receiveShadows;
  17194. },
  17195. set: function (value) {
  17196. if (this._receiveShadows === value) {
  17197. return;
  17198. }
  17199. this._receiveShadows = value;
  17200. this._markSubMeshesAsLightDirty();
  17201. },
  17202. enumerable: true,
  17203. configurable: true
  17204. });
  17205. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17206. get: function () {
  17207. return this._hasVertexAlpha;
  17208. },
  17209. set: function (value) {
  17210. if (this._hasVertexAlpha === value) {
  17211. return;
  17212. }
  17213. this._hasVertexAlpha = value;
  17214. this._markSubMeshesAsAttributesDirty();
  17215. this._markSubMeshesAsMiscDirty();
  17216. },
  17217. enumerable: true,
  17218. configurable: true
  17219. });
  17220. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17221. get: function () {
  17222. return this._useVertexColors;
  17223. },
  17224. set: function (value) {
  17225. if (this._useVertexColors === value) {
  17226. return;
  17227. }
  17228. this._useVertexColors = value;
  17229. this._markSubMeshesAsAttributesDirty();
  17230. },
  17231. enumerable: true,
  17232. configurable: true
  17233. });
  17234. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17235. get: function () {
  17236. return this._computeBonesUsingShaders;
  17237. },
  17238. set: function (value) {
  17239. if (this._computeBonesUsingShaders === value) {
  17240. return;
  17241. }
  17242. this._computeBonesUsingShaders = value;
  17243. this._markSubMeshesAsAttributesDirty();
  17244. },
  17245. enumerable: true,
  17246. configurable: true
  17247. });
  17248. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17249. get: function () {
  17250. return this._numBoneInfluencers;
  17251. },
  17252. set: function (value) {
  17253. if (this._numBoneInfluencers === value) {
  17254. return;
  17255. }
  17256. this._numBoneInfluencers = value;
  17257. this._markSubMeshesAsAttributesDirty();
  17258. },
  17259. enumerable: true,
  17260. configurable: true
  17261. });
  17262. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17263. get: function () {
  17264. return this._applyFog;
  17265. },
  17266. set: function (value) {
  17267. if (this._applyFog === value) {
  17268. return;
  17269. }
  17270. this._applyFog = value;
  17271. this._markSubMeshesAsMiscDirty();
  17272. },
  17273. enumerable: true,
  17274. configurable: true
  17275. });
  17276. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17277. get: function () {
  17278. return this._layerMask;
  17279. },
  17280. set: function (value) {
  17281. if (value === this._layerMask) {
  17282. return;
  17283. }
  17284. this._layerMask = value;
  17285. this._resyncLightSources();
  17286. },
  17287. enumerable: true,
  17288. configurable: true
  17289. });
  17290. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17291. get: function () {
  17292. return this._collisionMask;
  17293. },
  17294. set: function (mask) {
  17295. this._collisionMask = !isNaN(mask) ? mask : -1;
  17296. },
  17297. enumerable: true,
  17298. configurable: true
  17299. });
  17300. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17301. get: function () {
  17302. return this._collisionGroup;
  17303. },
  17304. set: function (mask) {
  17305. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17306. },
  17307. enumerable: true,
  17308. configurable: true
  17309. });
  17310. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17311. get: function () {
  17312. return null;
  17313. },
  17314. enumerable: true,
  17315. configurable: true
  17316. });
  17317. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17318. get: function () {
  17319. return this._skeleton;
  17320. },
  17321. set: function (value) {
  17322. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17323. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17324. }
  17325. if (value && value.needInitialSkinMatrix) {
  17326. value._registerMeshWithPoseMatrix(this);
  17327. }
  17328. this._skeleton = value;
  17329. if (!this._skeleton) {
  17330. this._bonesTransformMatrices = null;
  17331. }
  17332. this._markSubMeshesAsAttributesDirty();
  17333. },
  17334. enumerable: true,
  17335. configurable: true
  17336. });
  17337. /**
  17338. * Returns the string "AbstractMesh"
  17339. */
  17340. AbstractMesh.prototype.getClassName = function () {
  17341. return "AbstractMesh";
  17342. };
  17343. /**
  17344. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17345. */
  17346. AbstractMesh.prototype.toString = function (fullDetails) {
  17347. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17348. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17349. if (this._skeleton) {
  17350. ret += ", skeleton: " + this._skeleton.name;
  17351. }
  17352. if (fullDetails) {
  17353. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17354. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17355. }
  17356. return ret;
  17357. };
  17358. AbstractMesh.prototype._rebuild = function () {
  17359. if (this._occlusionQuery) {
  17360. this._occlusionQuery = null;
  17361. }
  17362. if (this._edgesRenderer) {
  17363. this._edgesRenderer._rebuild();
  17364. }
  17365. if (!this.subMeshes) {
  17366. return;
  17367. }
  17368. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17369. var subMesh = _a[_i];
  17370. subMesh._rebuild();
  17371. }
  17372. };
  17373. AbstractMesh.prototype._resyncLightSources = function () {
  17374. this._lightSources.length = 0;
  17375. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17376. var light = _a[_i];
  17377. if (!light.isEnabled()) {
  17378. continue;
  17379. }
  17380. if (light.canAffectMesh(this)) {
  17381. this._lightSources.push(light);
  17382. }
  17383. }
  17384. this._markSubMeshesAsLightDirty();
  17385. };
  17386. AbstractMesh.prototype._resyncLighSource = function (light) {
  17387. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17388. var index = this._lightSources.indexOf(light);
  17389. if (index === -1) {
  17390. if (!isIn) {
  17391. return;
  17392. }
  17393. this._lightSources.push(light);
  17394. }
  17395. else {
  17396. if (isIn) {
  17397. return;
  17398. }
  17399. this._lightSources.splice(index, 1);
  17400. }
  17401. this._markSubMeshesAsLightDirty();
  17402. };
  17403. AbstractMesh.prototype._removeLightSource = function (light) {
  17404. var index = this._lightSources.indexOf(light);
  17405. if (index === -1) {
  17406. return;
  17407. }
  17408. this._lightSources.splice(index, 1);
  17409. this._markSubMeshesAsLightDirty();
  17410. };
  17411. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17412. if (!this.subMeshes) {
  17413. return;
  17414. }
  17415. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17416. var subMesh = _a[_i];
  17417. if (subMesh._materialDefines) {
  17418. func(subMesh._materialDefines);
  17419. }
  17420. }
  17421. };
  17422. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17423. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17424. };
  17425. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17426. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17427. };
  17428. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17429. if (!this.subMeshes) {
  17430. return;
  17431. }
  17432. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17433. var subMesh = _a[_i];
  17434. var material = subMesh.getMaterial();
  17435. if (material) {
  17436. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17437. }
  17438. }
  17439. };
  17440. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17441. /**
  17442. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17443. * Default : (1.0, 1.0, 1.0)
  17444. */
  17445. get: function () {
  17446. return this._scaling;
  17447. },
  17448. /**
  17449. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17450. * Default : (1.0, 1.0, 1.0)
  17451. */
  17452. set: function (newScaling) {
  17453. this._scaling = newScaling;
  17454. if (this.physicsImpostor) {
  17455. this.physicsImpostor.forceUpdate();
  17456. }
  17457. },
  17458. enumerable: true,
  17459. configurable: true
  17460. });
  17461. // Methods
  17462. /**
  17463. * Disables the mesh edger rendering mode.
  17464. * Returns the AbstractMesh.
  17465. */
  17466. AbstractMesh.prototype.disableEdgesRendering = function () {
  17467. if (this._edgesRenderer) {
  17468. this._edgesRenderer.dispose();
  17469. this._edgesRenderer = null;
  17470. }
  17471. return this;
  17472. };
  17473. /**
  17474. * Enables the edge rendering mode on the mesh.
  17475. * This mode makes the mesh edges visible.
  17476. * Returns the AbstractMesh.
  17477. */
  17478. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17479. if (epsilon === void 0) { epsilon = 0.95; }
  17480. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17481. this.disableEdgesRendering();
  17482. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17483. return this;
  17484. };
  17485. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17486. /**
  17487. * Returns true if the mesh is blocked. Used by the class Mesh.
  17488. * Returns the boolean `false` by default.
  17489. */
  17490. get: function () {
  17491. return false;
  17492. },
  17493. enumerable: true,
  17494. configurable: true
  17495. });
  17496. /**
  17497. * Returns the mesh itself by default, used by the class Mesh.
  17498. * Returned type : AbstractMesh
  17499. */
  17500. AbstractMesh.prototype.getLOD = function (camera) {
  17501. return this;
  17502. };
  17503. /**
  17504. * Returns 0 by default, used by the class Mesh.
  17505. * Returns an integer.
  17506. */
  17507. AbstractMesh.prototype.getTotalVertices = function () {
  17508. return 0;
  17509. };
  17510. /**
  17511. * Returns null by default, used by the class Mesh.
  17512. * Returned type : integer array
  17513. */
  17514. AbstractMesh.prototype.getIndices = function () {
  17515. return null;
  17516. };
  17517. /**
  17518. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17519. * Returned type : float array or Float32Array
  17520. */
  17521. AbstractMesh.prototype.getVerticesData = function (kind) {
  17522. return null;
  17523. };
  17524. /**
  17525. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17526. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17527. * The `data` are either a numeric array either a Float32Array.
  17528. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17529. * 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).
  17530. * Note that a new underlying VertexBuffer object is created each call.
  17531. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17532. *
  17533. * Possible `kind` values :
  17534. * - BABYLON.VertexBuffer.PositionKind
  17535. * - BABYLON.VertexBuffer.UVKind
  17536. * - BABYLON.VertexBuffer.UV2Kind
  17537. * - BABYLON.VertexBuffer.UV3Kind
  17538. * - BABYLON.VertexBuffer.UV4Kind
  17539. * - BABYLON.VertexBuffer.UV5Kind
  17540. * - BABYLON.VertexBuffer.UV6Kind
  17541. * - BABYLON.VertexBuffer.ColorKind
  17542. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17543. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17544. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17545. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17546. *
  17547. * Returns the Mesh.
  17548. */
  17549. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17550. return this;
  17551. };
  17552. /**
  17553. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17554. * If the mesh has no geometry, it is simply returned as it is.
  17555. * The `data` are either a numeric array either a Float32Array.
  17556. * No new underlying VertexBuffer object is created.
  17557. * 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.
  17558. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17559. *
  17560. * Possible `kind` values :
  17561. * - BABYLON.VertexBuffer.PositionKind
  17562. * - BABYLON.VertexBuffer.UVKind
  17563. * - BABYLON.VertexBuffer.UV2Kind
  17564. * - BABYLON.VertexBuffer.UV3Kind
  17565. * - BABYLON.VertexBuffer.UV4Kind
  17566. * - BABYLON.VertexBuffer.UV5Kind
  17567. * - BABYLON.VertexBuffer.UV6Kind
  17568. * - BABYLON.VertexBuffer.ColorKind
  17569. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17570. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17571. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17572. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17573. *
  17574. * Returns the Mesh.
  17575. */
  17576. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17577. return this;
  17578. };
  17579. /**
  17580. * Sets the mesh indices.
  17581. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17582. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17583. * This method creates a new index buffer each call.
  17584. * Returns the Mesh.
  17585. */
  17586. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17587. return this;
  17588. };
  17589. /** Returns false by default, used by the class Mesh.
  17590. * Returns a boolean
  17591. */
  17592. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17593. return false;
  17594. };
  17595. /**
  17596. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17597. * Returns a BoundingInfo
  17598. */
  17599. AbstractMesh.prototype.getBoundingInfo = function () {
  17600. if (this._masterMesh) {
  17601. return this._masterMesh.getBoundingInfo();
  17602. }
  17603. if (!this._boundingInfo) {
  17604. // this._boundingInfo is being created here
  17605. this._updateBoundingInfo();
  17606. }
  17607. // cannot be null.
  17608. return this._boundingInfo;
  17609. };
  17610. /**
  17611. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17612. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17613. */
  17614. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17615. if (includeDescendants === void 0) { includeDescendants = true; }
  17616. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17617. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17618. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17619. if (maxDimension === 0) {
  17620. return this;
  17621. }
  17622. var scale = 1 / maxDimension;
  17623. this.scaling.scaleInPlace(scale);
  17624. return this;
  17625. };
  17626. /**
  17627. * Sets a mesh new object BoundingInfo.
  17628. * Returns the AbstractMesh.
  17629. */
  17630. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17631. this._boundingInfo = boundingInfo;
  17632. return this;
  17633. };
  17634. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17635. get: function () {
  17636. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17637. },
  17638. enumerable: true,
  17639. configurable: true
  17640. });
  17641. AbstractMesh.prototype._preActivate = function () {
  17642. };
  17643. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17644. };
  17645. AbstractMesh.prototype._activate = function (renderId) {
  17646. this._renderId = renderId;
  17647. };
  17648. /**
  17649. * Returns the latest update of the World matrix
  17650. * Returns a Matrix.
  17651. */
  17652. AbstractMesh.prototype.getWorldMatrix = function () {
  17653. if (this._masterMesh) {
  17654. return this._masterMesh.getWorldMatrix();
  17655. }
  17656. return _super.prototype.getWorldMatrix.call(this);
  17657. };
  17658. /**
  17659. * Returns the latest update of the World matrix determinant.
  17660. */
  17661. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17662. if (this._masterMesh) {
  17663. return this._masterMesh._getWorldMatrixDeterminant();
  17664. }
  17665. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17666. };
  17667. // ================================== Point of View Movement =================================
  17668. /**
  17669. * Perform relative position change from the point of view of behind the front of the mesh.
  17670. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17671. * Supports definition of mesh facing forward or backward.
  17672. * @param {number} amountRight
  17673. * @param {number} amountUp
  17674. * @param {number} amountForward
  17675. *
  17676. * Returns the AbstractMesh.
  17677. */
  17678. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17679. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17680. return this;
  17681. };
  17682. /**
  17683. * Calculate relative position change from the point of view of behind the front of the mesh.
  17684. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17685. * Supports definition of mesh facing forward or backward.
  17686. * @param {number} amountRight
  17687. * @param {number} amountUp
  17688. * @param {number} amountForward
  17689. *
  17690. * Returns a new Vector3.
  17691. */
  17692. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17693. var rotMatrix = new BABYLON.Matrix();
  17694. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17695. rotQuaternion.toRotationMatrix(rotMatrix);
  17696. var translationDelta = BABYLON.Vector3.Zero();
  17697. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17698. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17699. return translationDelta;
  17700. };
  17701. // ================================== Point of View Rotation =================================
  17702. /**
  17703. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17704. * Supports definition of mesh facing forward or backward.
  17705. * @param {number} flipBack
  17706. * @param {number} twirlClockwise
  17707. * @param {number} tiltRight
  17708. *
  17709. * Returns the AbstractMesh.
  17710. */
  17711. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17712. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17713. return this;
  17714. };
  17715. /**
  17716. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17717. * Supports definition of mesh facing forward or backward.
  17718. * @param {number} flipBack
  17719. * @param {number} twirlClockwise
  17720. * @param {number} tiltRight
  17721. *
  17722. * Returns a new Vector3.
  17723. */
  17724. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17725. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17726. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17727. };
  17728. /**
  17729. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17730. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17731. */
  17732. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17733. if (includeDescendants === void 0) { includeDescendants = true; }
  17734. this.computeWorldMatrix(true);
  17735. var min;
  17736. var max;
  17737. var boundingInfo = this.getBoundingInfo();
  17738. if (!this.subMeshes) {
  17739. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17740. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17741. }
  17742. else {
  17743. min = boundingInfo.boundingBox.minimumWorld;
  17744. max = boundingInfo.boundingBox.maximumWorld;
  17745. }
  17746. if (includeDescendants) {
  17747. var descendants = this.getDescendants(false);
  17748. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  17749. var descendant = descendants_1[_i];
  17750. var childMesh = descendant;
  17751. childMesh.computeWorldMatrix(true);
  17752. //make sure we have the needed params to get mix and max
  17753. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  17754. continue;
  17755. }
  17756. var childBoundingInfo = childMesh.getBoundingInfo();
  17757. var boundingBox = childBoundingInfo.boundingBox;
  17758. var minBox = boundingBox.minimumWorld;
  17759. var maxBox = boundingBox.maximumWorld;
  17760. BABYLON.Tools.CheckExtends(minBox, min, max);
  17761. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17762. }
  17763. }
  17764. return {
  17765. min: min,
  17766. max: max
  17767. };
  17768. };
  17769. /**
  17770. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  17771. * Returns the AbstractMesh.
  17772. */
  17773. AbstractMesh.prototype._updateBoundingInfo = function () {
  17774. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  17775. this._boundingInfo.update(this.worldMatrixFromCache);
  17776. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17777. return this;
  17778. };
  17779. /**
  17780. * Update a mesh's children BoundingInfo objects only.
  17781. * Returns the AbstractMesh.
  17782. */
  17783. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  17784. if (!this.subMeshes) {
  17785. return this;
  17786. }
  17787. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  17788. var subMesh = this.subMeshes[subIndex];
  17789. if (!subMesh.IsGlobal) {
  17790. subMesh.updateBoundingInfo(matrix);
  17791. }
  17792. }
  17793. return this;
  17794. };
  17795. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  17796. // Bounding info
  17797. this._updateBoundingInfo();
  17798. };
  17799. /**
  17800. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  17801. * A mesh is in the frustum if its bounding box intersects the frustum.
  17802. * Boolean returned.
  17803. */
  17804. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  17805. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  17806. };
  17807. /**
  17808. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  17809. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  17810. * Boolean returned.
  17811. */
  17812. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17813. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  17814. ;
  17815. };
  17816. /**
  17817. * True if the mesh intersects another mesh or a SolidParticle object.
  17818. * 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)
  17819. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  17820. * Returns a boolean.
  17821. */
  17822. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  17823. if (precise === void 0) { precise = false; }
  17824. if (!this._boundingInfo || !mesh._boundingInfo) {
  17825. return false;
  17826. }
  17827. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  17828. return true;
  17829. }
  17830. if (includeDescendants) {
  17831. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  17832. var child = _a[_i];
  17833. if (child.intersectsMesh(mesh, precise, true)) {
  17834. return true;
  17835. }
  17836. }
  17837. }
  17838. return false;
  17839. };
  17840. /**
  17841. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  17842. * Returns a boolean.
  17843. */
  17844. AbstractMesh.prototype.intersectsPoint = function (point) {
  17845. if (!this._boundingInfo) {
  17846. return false;
  17847. }
  17848. return this._boundingInfo.intersectsPoint(point);
  17849. };
  17850. AbstractMesh.prototype.getPhysicsImpostor = function () {
  17851. return this.physicsImpostor;
  17852. };
  17853. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  17854. if (camera === void 0) { camera = null; }
  17855. if (!camera) {
  17856. camera = this.getScene().activeCamera;
  17857. }
  17858. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  17859. };
  17860. /**
  17861. * Returns the distance from the mesh to the active camera.
  17862. * Returns a float.
  17863. */
  17864. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  17865. if (camera === void 0) { camera = null; }
  17866. if (!camera) {
  17867. camera = this.getScene().activeCamera;
  17868. }
  17869. return this.absolutePosition.subtract(camera.position).length();
  17870. };
  17871. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  17872. if (!this.physicsImpostor) {
  17873. return this;
  17874. }
  17875. this.physicsImpostor.applyImpulse(force, contactPoint);
  17876. return this;
  17877. };
  17878. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  17879. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  17880. return this;
  17881. }
  17882. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  17883. mainPivot: pivot1,
  17884. connectedPivot: pivot2,
  17885. nativeParams: options
  17886. });
  17887. return this;
  17888. };
  17889. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  17890. // Collisions
  17891. /**
  17892. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  17893. * Default `false`.
  17894. */
  17895. get: function () {
  17896. return this._checkCollisions;
  17897. },
  17898. set: function (collisionEnabled) {
  17899. this._checkCollisions = collisionEnabled;
  17900. if (this.getScene().workerCollisions) {
  17901. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17902. }
  17903. },
  17904. enumerable: true,
  17905. configurable: true
  17906. });
  17907. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17908. /**
  17909. * Gets Collider object used to compute collisions (not physics)
  17910. */
  17911. get: function () {
  17912. return this._collider;
  17913. },
  17914. enumerable: true,
  17915. configurable: true
  17916. });
  17917. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17918. var globalPosition = this.getAbsolutePosition();
  17919. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17920. if (!this._collider) {
  17921. this._collider = new BABYLON.Collider();
  17922. }
  17923. this._collider._radius = this.ellipsoid;
  17924. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17925. return this;
  17926. };
  17927. // Submeshes octree
  17928. /**
  17929. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17930. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17931. * Returns an Octree of submeshes.
  17932. */
  17933. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17934. if (maxCapacity === void 0) { maxCapacity = 64; }
  17935. if (maxDepth === void 0) { maxDepth = 2; }
  17936. if (!this._submeshesOctree) {
  17937. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17938. }
  17939. this.computeWorldMatrix(true);
  17940. var boundingInfo = this.getBoundingInfo();
  17941. // Update octree
  17942. var bbox = boundingInfo.boundingBox;
  17943. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17944. return this._submeshesOctree;
  17945. };
  17946. // Collisions
  17947. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17948. this._generatePointsArray();
  17949. if (!this._positions) {
  17950. return this;
  17951. }
  17952. // Transformation
  17953. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17954. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17955. subMesh._lastColliderWorldVertices = [];
  17956. subMesh._trianglePlanes = [];
  17957. var start = subMesh.verticesStart;
  17958. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17959. for (var i = start; i < end; i++) {
  17960. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17961. }
  17962. }
  17963. // Collide
  17964. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17965. if (collider.collisionFound) {
  17966. collider.collidedMesh = this;
  17967. }
  17968. return this;
  17969. };
  17970. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17971. var subMeshes;
  17972. var len;
  17973. // Octrees
  17974. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17975. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17976. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17977. len = intersections.length;
  17978. subMeshes = intersections.data;
  17979. }
  17980. else {
  17981. subMeshes = this.subMeshes;
  17982. len = subMeshes.length;
  17983. }
  17984. for (var index = 0; index < len; index++) {
  17985. var subMesh = subMeshes[index];
  17986. // Bounding test
  17987. if (len > 1 && !subMesh._checkCollision(collider))
  17988. continue;
  17989. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17990. }
  17991. return this;
  17992. };
  17993. AbstractMesh.prototype._checkCollision = function (collider) {
  17994. // Bounding box test
  17995. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17996. return this;
  17997. // Transformation matrix
  17998. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17999. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18000. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18001. return this;
  18002. };
  18003. // Picking
  18004. AbstractMesh.prototype._generatePointsArray = function () {
  18005. return false;
  18006. };
  18007. /**
  18008. * Checks if the passed Ray intersects with the mesh.
  18009. * Returns an object PickingInfo.
  18010. */
  18011. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18012. var pickingInfo = new BABYLON.PickingInfo();
  18013. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18014. return pickingInfo;
  18015. }
  18016. if (!this._generatePointsArray()) {
  18017. return pickingInfo;
  18018. }
  18019. var intersectInfo = null;
  18020. // Octrees
  18021. var subMeshes;
  18022. var len;
  18023. if (this._submeshesOctree && this.useOctreeForPicking) {
  18024. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18025. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18026. len = intersections.length;
  18027. subMeshes = intersections.data;
  18028. }
  18029. else {
  18030. subMeshes = this.subMeshes;
  18031. len = subMeshes.length;
  18032. }
  18033. for (var index = 0; index < len; index++) {
  18034. var subMesh = subMeshes[index];
  18035. // Bounding test
  18036. if (len > 1 && !subMesh.canIntersects(ray))
  18037. continue;
  18038. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18039. if (currentIntersectInfo) {
  18040. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18041. intersectInfo = currentIntersectInfo;
  18042. intersectInfo.subMeshId = index;
  18043. if (fastCheck) {
  18044. break;
  18045. }
  18046. }
  18047. }
  18048. }
  18049. if (intersectInfo) {
  18050. // Get picked point
  18051. var world = this.getWorldMatrix();
  18052. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18053. var direction = ray.direction.clone();
  18054. direction = direction.scale(intersectInfo.distance);
  18055. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18056. var pickedPoint = worldOrigin.add(worldDirection);
  18057. // Return result
  18058. pickingInfo.hit = true;
  18059. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18060. pickingInfo.pickedPoint = pickedPoint;
  18061. pickingInfo.pickedMesh = this;
  18062. pickingInfo.bu = intersectInfo.bu || 0;
  18063. pickingInfo.bv = intersectInfo.bv || 0;
  18064. pickingInfo.faceId = intersectInfo.faceId;
  18065. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18066. return pickingInfo;
  18067. }
  18068. return pickingInfo;
  18069. };
  18070. /**
  18071. * Clones the mesh, used by the class Mesh.
  18072. * Just returns `null` for an AbstractMesh.
  18073. */
  18074. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18075. return null;
  18076. };
  18077. /**
  18078. * Disposes all the mesh submeshes.
  18079. * Returns the AbstractMesh.
  18080. */
  18081. AbstractMesh.prototype.releaseSubMeshes = function () {
  18082. if (this.subMeshes) {
  18083. while (this.subMeshes.length) {
  18084. this.subMeshes[0].dispose();
  18085. }
  18086. }
  18087. else {
  18088. this.subMeshes = new Array();
  18089. }
  18090. return this;
  18091. };
  18092. /**
  18093. * Disposes the AbstractMesh.
  18094. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  18095. * Returns nothing.
  18096. */
  18097. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18098. var _this = this;
  18099. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18100. var index;
  18101. // Action manager
  18102. if (this.actionManager !== undefined && this.actionManager !== null) {
  18103. this.actionManager.dispose();
  18104. this.actionManager = null;
  18105. }
  18106. // Skeleton
  18107. this.skeleton = null;
  18108. // Physics
  18109. if (this.physicsImpostor) {
  18110. this.physicsImpostor.dispose();
  18111. }
  18112. // Intersections in progress
  18113. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18114. var other = this._intersectionsInProgress[index];
  18115. var pos = other._intersectionsInProgress.indexOf(this);
  18116. other._intersectionsInProgress.splice(pos, 1);
  18117. }
  18118. this._intersectionsInProgress = [];
  18119. // Lights
  18120. var lights = this.getScene().lights;
  18121. lights.forEach(function (light) {
  18122. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18123. if (meshIndex !== -1) {
  18124. light.includedOnlyMeshes.splice(meshIndex, 1);
  18125. }
  18126. meshIndex = light.excludedMeshes.indexOf(_this);
  18127. if (meshIndex !== -1) {
  18128. light.excludedMeshes.splice(meshIndex, 1);
  18129. }
  18130. // Shadow generators
  18131. var generator = light.getShadowGenerator();
  18132. if (generator) {
  18133. var shadowMap = generator.getShadowMap();
  18134. if (shadowMap && shadowMap.renderList) {
  18135. meshIndex = shadowMap.renderList.indexOf(_this);
  18136. if (meshIndex !== -1) {
  18137. shadowMap.renderList.splice(meshIndex, 1);
  18138. }
  18139. }
  18140. }
  18141. });
  18142. // Edges
  18143. if (this._edgesRenderer) {
  18144. this._edgesRenderer.dispose();
  18145. this._edgesRenderer = null;
  18146. }
  18147. // SubMeshes
  18148. if (this.getClassName() !== "InstancedMesh") {
  18149. this.releaseSubMeshes();
  18150. }
  18151. // Octree
  18152. var sceneOctree = this.getScene().selectionOctree;
  18153. if (sceneOctree !== undefined && sceneOctree !== null) {
  18154. var index = sceneOctree.dynamicContent.indexOf(this);
  18155. if (index !== -1) {
  18156. sceneOctree.dynamicContent.splice(index, 1);
  18157. }
  18158. }
  18159. // Query
  18160. var engine = this.getScene().getEngine();
  18161. if (this._occlusionQuery) {
  18162. this._isOcclusionQueryInProgress = false;
  18163. engine.deleteQuery(this._occlusionQuery);
  18164. this._occlusionQuery = null;
  18165. }
  18166. // Engine
  18167. engine.wipeCaches();
  18168. // Remove from scene
  18169. this.getScene().removeMesh(this);
  18170. if (disposeMaterialAndTextures) {
  18171. if (this.material) {
  18172. this.material.dispose(false, true);
  18173. }
  18174. }
  18175. if (!doNotRecurse) {
  18176. // Particles
  18177. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18178. if (this.getScene().particleSystems[index].emitter === this) {
  18179. this.getScene().particleSystems[index].dispose();
  18180. index--;
  18181. }
  18182. }
  18183. }
  18184. // facet data
  18185. if (this._facetDataEnabled) {
  18186. this.disableFacetData();
  18187. }
  18188. this.onAfterWorldMatrixUpdateObservable.clear();
  18189. this.onCollideObservable.clear();
  18190. this.onCollisionPositionChangeObservable.clear();
  18191. _super.prototype.dispose.call(this, doNotRecurse);
  18192. };
  18193. /**
  18194. * Adds the passed mesh as a child to the current mesh.
  18195. * Returns the AbstractMesh.
  18196. */
  18197. AbstractMesh.prototype.addChild = function (mesh) {
  18198. mesh.setParent(this);
  18199. return this;
  18200. };
  18201. /**
  18202. * Removes the passed mesh from the current mesh children list.
  18203. * Returns the AbstractMesh.
  18204. */
  18205. AbstractMesh.prototype.removeChild = function (mesh) {
  18206. mesh.setParent(null);
  18207. return this;
  18208. };
  18209. // Facet data
  18210. /**
  18211. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18212. * Returns the AbstractMesh.
  18213. */
  18214. AbstractMesh.prototype._initFacetData = function () {
  18215. if (!this._facetNormals) {
  18216. this._facetNormals = new Array();
  18217. }
  18218. if (!this._facetPositions) {
  18219. this._facetPositions = new Array();
  18220. }
  18221. if (!this._facetPartitioning) {
  18222. this._facetPartitioning = new Array();
  18223. }
  18224. this._facetNb = (this.getIndices().length / 3) | 0;
  18225. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18226. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18227. for (var f = 0; f < this._facetNb; f++) {
  18228. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18229. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18230. }
  18231. this._facetDataEnabled = true;
  18232. return this;
  18233. };
  18234. /**
  18235. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18236. * This method can be called within the render loop.
  18237. * 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.
  18238. * Returns the AbstractMesh.
  18239. */
  18240. AbstractMesh.prototype.updateFacetData = function () {
  18241. if (!this._facetDataEnabled) {
  18242. this._initFacetData();
  18243. }
  18244. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18245. var indices = this.getIndices();
  18246. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18247. var bInfo = this.getBoundingInfo();
  18248. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18249. // init arrays, matrix and sort function on first call
  18250. this._facetDepthSortEnabled = true;
  18251. if (indices instanceof Uint16Array) {
  18252. this._depthSortedIndices = new Uint16Array(indices);
  18253. }
  18254. else if (indices instanceof Uint32Array) {
  18255. this._depthSortedIndices = new Uint32Array(indices);
  18256. }
  18257. else {
  18258. var needs32bits = false;
  18259. for (var i = 0; i < indices.length; i++) {
  18260. if (indices[i] > 65535) {
  18261. needs32bits = true;
  18262. break;
  18263. }
  18264. }
  18265. if (needs32bits) {
  18266. this._depthSortedIndices = new Uint32Array(indices);
  18267. }
  18268. else {
  18269. this._depthSortedIndices = new Uint16Array(indices);
  18270. }
  18271. }
  18272. this._facetDepthSortFunction = function (f1, f2) {
  18273. return (f2.sqDistance - f1.sqDistance);
  18274. };
  18275. if (!this._facetDepthSortFrom) {
  18276. var camera = this.getScene().activeCamera;
  18277. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18278. }
  18279. this._depthSortedFacets = [];
  18280. for (var f = 0; f < this._facetNb; f++) {
  18281. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18282. this._depthSortedFacets.push(depthSortedFacet);
  18283. }
  18284. this._invertedMatrix = BABYLON.Matrix.Identity();
  18285. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18286. }
  18287. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18288. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18289. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18290. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18291. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18292. this._subDiv.max = this._partitioningSubdivisions;
  18293. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18294. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18295. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18296. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18297. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18298. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18299. // set the parameters for ComputeNormals()
  18300. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18301. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18302. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18303. this._facetParameters.bInfo = bInfo;
  18304. this._facetParameters.bbSize = this._bbSize;
  18305. this._facetParameters.subDiv = this._subDiv;
  18306. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18307. this._facetParameters.depthSort = this._facetDepthSort;
  18308. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18309. this.computeWorldMatrix(true);
  18310. this._worldMatrix.invertToRef(this._invertedMatrix);
  18311. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18312. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18313. }
  18314. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18315. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18316. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18317. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18318. var l = (this._depthSortedIndices.length / 3) | 0;
  18319. for (var f = 0; f < l; f++) {
  18320. var sind = this._depthSortedFacets[f].ind;
  18321. this._depthSortedIndices[f * 3] = indices[sind];
  18322. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18323. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18324. }
  18325. this.updateIndices(this._depthSortedIndices);
  18326. }
  18327. return this;
  18328. };
  18329. /**
  18330. * Returns the facetLocalNormals array.
  18331. * The normals are expressed in the mesh local space.
  18332. */
  18333. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18334. if (!this._facetNormals) {
  18335. this.updateFacetData();
  18336. }
  18337. return this._facetNormals;
  18338. };
  18339. /**
  18340. * Returns the facetLocalPositions array.
  18341. * The facet positions are expressed in the mesh local space.
  18342. */
  18343. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18344. if (!this._facetPositions) {
  18345. this.updateFacetData();
  18346. }
  18347. return this._facetPositions;
  18348. };
  18349. /**
  18350. * Returns the facetLocalPartioning array.
  18351. */
  18352. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18353. if (!this._facetPartitioning) {
  18354. this.updateFacetData();
  18355. }
  18356. return this._facetPartitioning;
  18357. };
  18358. /**
  18359. * Returns the i-th facet position in the world system.
  18360. * This method allocates a new Vector3 per call.
  18361. */
  18362. AbstractMesh.prototype.getFacetPosition = function (i) {
  18363. var pos = BABYLON.Vector3.Zero();
  18364. this.getFacetPositionToRef(i, pos);
  18365. return pos;
  18366. };
  18367. /**
  18368. * Sets the reference Vector3 with the i-th facet position in the world system.
  18369. * Returns the AbstractMesh.
  18370. */
  18371. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18372. var localPos = (this.getFacetLocalPositions())[i];
  18373. var world = this.getWorldMatrix();
  18374. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18375. return this;
  18376. };
  18377. /**
  18378. * Returns the i-th facet normal in the world system.
  18379. * This method allocates a new Vector3 per call.
  18380. */
  18381. AbstractMesh.prototype.getFacetNormal = function (i) {
  18382. var norm = BABYLON.Vector3.Zero();
  18383. this.getFacetNormalToRef(i, norm);
  18384. return norm;
  18385. };
  18386. /**
  18387. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18388. * Returns the AbstractMesh.
  18389. */
  18390. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18391. var localNorm = (this.getFacetLocalNormals())[i];
  18392. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18393. return this;
  18394. };
  18395. /**
  18396. * 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).
  18397. */
  18398. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18399. var bInfo = this.getBoundingInfo();
  18400. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18401. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18402. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18403. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18404. return null;
  18405. }
  18406. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18407. };
  18408. /**
  18409. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18410. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18411. * 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.
  18412. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18413. * 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.
  18414. */
  18415. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18416. if (checkFace === void 0) { checkFace = false; }
  18417. if (facing === void 0) { facing = true; }
  18418. var world = this.getWorldMatrix();
  18419. var invMat = BABYLON.Tmp.Matrix[5];
  18420. world.invertToRef(invMat);
  18421. var invVect = BABYLON.Tmp.Vector3[8];
  18422. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18423. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18424. if (projected) {
  18425. // tranform the local computed projected vector to world coordinates
  18426. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18427. }
  18428. return closest;
  18429. };
  18430. /**
  18431. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18432. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18433. * 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.
  18434. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18435. * 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.
  18436. */
  18437. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18438. if (checkFace === void 0) { checkFace = false; }
  18439. if (facing === void 0) { facing = true; }
  18440. var closest = null;
  18441. var tmpx = 0.0;
  18442. var tmpy = 0.0;
  18443. var tmpz = 0.0;
  18444. var d = 0.0; // tmp dot facet normal * facet position
  18445. var t0 = 0.0;
  18446. var projx = 0.0;
  18447. var projy = 0.0;
  18448. var projz = 0.0;
  18449. // Get all the facets in the same partitioning block than (x, y, z)
  18450. var facetPositions = this.getFacetLocalPositions();
  18451. var facetNormals = this.getFacetLocalNormals();
  18452. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18453. if (!facetsInBlock) {
  18454. return null;
  18455. }
  18456. // Get the closest facet to (x, y, z)
  18457. var shortest = Number.MAX_VALUE; // init distance vars
  18458. var tmpDistance = shortest;
  18459. var fib; // current facet in the block
  18460. var norm; // current facet normal
  18461. var p0; // current facet barycenter position
  18462. // loop on all the facets in the current partitioning block
  18463. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18464. fib = facetsInBlock[idx];
  18465. norm = facetNormals[fib];
  18466. p0 = facetPositions[fib];
  18467. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18468. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18469. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18470. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18471. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18472. projx = x + norm.x * t0;
  18473. projy = y + norm.y * t0;
  18474. projz = z + norm.z * t0;
  18475. tmpx = projx - x;
  18476. tmpy = projy - y;
  18477. tmpz = projz - z;
  18478. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18479. if (tmpDistance < shortest) {
  18480. shortest = tmpDistance;
  18481. closest = fib;
  18482. if (projected) {
  18483. projected.x = projx;
  18484. projected.y = projy;
  18485. projected.z = projz;
  18486. }
  18487. }
  18488. }
  18489. }
  18490. return closest;
  18491. };
  18492. /**
  18493. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18494. */
  18495. AbstractMesh.prototype.getFacetDataParameters = function () {
  18496. return this._facetParameters;
  18497. };
  18498. /**
  18499. * Disables the feature FacetData and frees the related memory.
  18500. * Returns the AbstractMesh.
  18501. */
  18502. AbstractMesh.prototype.disableFacetData = function () {
  18503. if (this._facetDataEnabled) {
  18504. this._facetDataEnabled = false;
  18505. this._facetPositions = new Array();
  18506. this._facetNormals = new Array();
  18507. this._facetPartitioning = new Array();
  18508. this._facetParameters = null;
  18509. this._depthSortedIndices = new Uint32Array(0);
  18510. }
  18511. return this;
  18512. };
  18513. /**
  18514. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18515. * Returns the mesh.
  18516. */
  18517. AbstractMesh.prototype.updateIndices = function (indices) {
  18518. return this;
  18519. };
  18520. /**
  18521. * The mesh Geometry. Actually used by the Mesh object.
  18522. * Returns a blank geometry object.
  18523. */
  18524. /**
  18525. * Creates new normals data for the mesh.
  18526. * @param updatable.
  18527. */
  18528. AbstractMesh.prototype.createNormals = function (updatable) {
  18529. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18530. var indices = this.getIndices();
  18531. var normals;
  18532. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18533. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18534. }
  18535. else {
  18536. normals = [];
  18537. }
  18538. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18539. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18540. };
  18541. /**
  18542. * Align the mesh with a normal.
  18543. * Returns the mesh.
  18544. */
  18545. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18546. if (!upDirection) {
  18547. upDirection = BABYLON.Axis.Y;
  18548. }
  18549. var axisX = BABYLON.Tmp.Vector3[0];
  18550. var axisZ = BABYLON.Tmp.Vector3[1];
  18551. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18552. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18553. if (this.rotationQuaternion) {
  18554. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18555. }
  18556. else {
  18557. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18558. }
  18559. return this;
  18560. };
  18561. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18562. var engine = this.getEngine();
  18563. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18564. this._isOccluded = false;
  18565. return;
  18566. }
  18567. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18568. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18569. if (isOcclusionQueryAvailable) {
  18570. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18571. this._isOcclusionQueryInProgress = false;
  18572. this._occlusionInternalRetryCounter = 0;
  18573. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18574. }
  18575. else {
  18576. this._occlusionInternalRetryCounter++;
  18577. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18578. this._isOcclusionQueryInProgress = false;
  18579. this._occlusionInternalRetryCounter = 0;
  18580. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18581. // if strict continue the last state of the object.
  18582. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18583. }
  18584. else {
  18585. return;
  18586. }
  18587. }
  18588. }
  18589. var scene = this.getScene();
  18590. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18591. if (!this._occlusionQuery) {
  18592. this._occlusionQuery = engine.createQuery();
  18593. }
  18594. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18595. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18596. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18597. this._isOcclusionQueryInProgress = true;
  18598. };
  18599. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18600. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18601. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18602. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18603. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18604. return AbstractMesh;
  18605. }(BABYLON.TransformNode));
  18606. BABYLON.AbstractMesh = AbstractMesh;
  18607. })(BABYLON || (BABYLON = {}));
  18608. //# sourceMappingURL=babylon.abstractMesh.js.map
  18609. var BABYLON;
  18610. (function (BABYLON) {
  18611. /**
  18612. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18613. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18614. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  18615. */
  18616. var Light = /** @class */ (function (_super) {
  18617. __extends(Light, _super);
  18618. /**
  18619. * Creates a Light object in the scene.
  18620. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18621. * @param name The firendly name of the light
  18622. * @param scene The scene the light belongs too
  18623. */
  18624. function Light(name, scene) {
  18625. var _this = _super.call(this, name, scene) || this;
  18626. /**
  18627. * Diffuse gives the basic color to an object.
  18628. */
  18629. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18630. /**
  18631. * Specular produces a highlight color on an object.
  18632. * Note: This is note affecting PBR materials.
  18633. */
  18634. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18635. /**
  18636. * Strength of the light.
  18637. * Note: By default it is define in the framework own unit.
  18638. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18639. */
  18640. _this.intensity = 1.0;
  18641. /**
  18642. * Defines how far from the source the light is impacting in scene units.
  18643. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18644. */
  18645. _this.range = Number.MAX_VALUE;
  18646. /**
  18647. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18648. * of light.
  18649. */
  18650. _this._photometricScale = 1.0;
  18651. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18652. _this._radius = 0.00001;
  18653. /**
  18654. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18655. * exceeding the number allowed of the materials.
  18656. */
  18657. _this.renderPriority = 0;
  18658. /**
  18659. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18660. * the current shadow generator.
  18661. */
  18662. _this.shadowEnabled = true;
  18663. _this._excludeWithLayerMask = 0;
  18664. _this._includeOnlyWithLayerMask = 0;
  18665. _this._lightmapMode = 0;
  18666. /**
  18667. * @ignore Internal use only.
  18668. */
  18669. _this._excludedMeshesIds = new Array();
  18670. /**
  18671. * @ignore Internal use only.
  18672. */
  18673. _this._includedOnlyMeshesIds = new Array();
  18674. _this.getScene().addLight(_this);
  18675. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18676. _this._buildUniformLayout();
  18677. _this.includedOnlyMeshes = new Array();
  18678. _this.excludedMeshes = new Array();
  18679. _this._resyncMeshes();
  18680. return _this;
  18681. }
  18682. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18683. /**
  18684. * If every light affecting the material is in this lightmapMode,
  18685. * material.lightmapTexture adds or multiplies
  18686. * (depends on material.useLightmapAsShadowmap)
  18687. * after every other light calculations.
  18688. */
  18689. get: function () {
  18690. return Light._LIGHTMAP_DEFAULT;
  18691. },
  18692. enumerable: true,
  18693. configurable: true
  18694. });
  18695. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18696. /**
  18697. * material.lightmapTexture as only diffuse lighting from this light
  18698. * adds only specular lighting from this light
  18699. * adds dynamic shadows
  18700. */
  18701. get: function () {
  18702. return Light._LIGHTMAP_SPECULAR;
  18703. },
  18704. enumerable: true,
  18705. configurable: true
  18706. });
  18707. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18708. /**
  18709. * material.lightmapTexture as only lighting
  18710. * no light calculation from this light
  18711. * only adds dynamic shadows from this light
  18712. */
  18713. get: function () {
  18714. return Light._LIGHTMAP_SHADOWSONLY;
  18715. },
  18716. enumerable: true,
  18717. configurable: true
  18718. });
  18719. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18720. /**
  18721. * Each light type uses the default quantity according to its type:
  18722. * point/spot lights use luminous intensity
  18723. * directional lights use illuminance
  18724. */
  18725. get: function () {
  18726. return Light._INTENSITYMODE_AUTOMATIC;
  18727. },
  18728. enumerable: true,
  18729. configurable: true
  18730. });
  18731. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18732. /**
  18733. * lumen (lm)
  18734. */
  18735. get: function () {
  18736. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18737. },
  18738. enumerable: true,
  18739. configurable: true
  18740. });
  18741. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18742. /**
  18743. * candela (lm/sr)
  18744. */
  18745. get: function () {
  18746. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  18747. },
  18748. enumerable: true,
  18749. configurable: true
  18750. });
  18751. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  18752. /**
  18753. * lux (lm/m^2)
  18754. */
  18755. get: function () {
  18756. return Light._INTENSITYMODE_ILLUMINANCE;
  18757. },
  18758. enumerable: true,
  18759. configurable: true
  18760. });
  18761. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  18762. /**
  18763. * nit (cd/m^2)
  18764. */
  18765. get: function () {
  18766. return Light._INTENSITYMODE_LUMINANCE;
  18767. },
  18768. enumerable: true,
  18769. configurable: true
  18770. });
  18771. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  18772. /**
  18773. * Light type const id of the point light.
  18774. */
  18775. get: function () {
  18776. return Light._LIGHTTYPEID_POINTLIGHT;
  18777. },
  18778. enumerable: true,
  18779. configurable: true
  18780. });
  18781. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  18782. /**
  18783. * Light type const id of the directional light.
  18784. */
  18785. get: function () {
  18786. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  18787. },
  18788. enumerable: true,
  18789. configurable: true
  18790. });
  18791. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  18792. /**
  18793. * Light type const id of the spot light.
  18794. */
  18795. get: function () {
  18796. return Light._LIGHTTYPEID_SPOTLIGHT;
  18797. },
  18798. enumerable: true,
  18799. configurable: true
  18800. });
  18801. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  18802. /**
  18803. * Light type const id of the hemispheric light.
  18804. */
  18805. get: function () {
  18806. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  18807. },
  18808. enumerable: true,
  18809. configurable: true
  18810. });
  18811. Object.defineProperty(Light.prototype, "intensityMode", {
  18812. /**
  18813. * Gets the photometric scale used to interpret the intensity.
  18814. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18815. */
  18816. get: function () {
  18817. return this._intensityMode;
  18818. },
  18819. /**
  18820. * Sets the photometric scale used to interpret the intensity.
  18821. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18822. */
  18823. set: function (value) {
  18824. this._intensityMode = value;
  18825. this._computePhotometricScale();
  18826. },
  18827. enumerable: true,
  18828. configurable: true
  18829. });
  18830. ;
  18831. ;
  18832. Object.defineProperty(Light.prototype, "radius", {
  18833. /**
  18834. * Gets the light radius used by PBR Materials to simulate soft area lights.
  18835. */
  18836. get: function () {
  18837. return this._radius;
  18838. },
  18839. /**
  18840. * sets the light radius used by PBR Materials to simulate soft area lights.
  18841. */
  18842. set: function (value) {
  18843. this._radius = value;
  18844. this._computePhotometricScale();
  18845. },
  18846. enumerable: true,
  18847. configurable: true
  18848. });
  18849. ;
  18850. ;
  18851. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  18852. /**
  18853. * Gets the only meshes impacted by this light.
  18854. */
  18855. get: function () {
  18856. return this._includedOnlyMeshes;
  18857. },
  18858. /**
  18859. * Sets the only meshes impacted by this light.
  18860. */
  18861. set: function (value) {
  18862. this._includedOnlyMeshes = value;
  18863. this._hookArrayForIncludedOnly(value);
  18864. },
  18865. enumerable: true,
  18866. configurable: true
  18867. });
  18868. Object.defineProperty(Light.prototype, "excludedMeshes", {
  18869. /**
  18870. * Gets the meshes not impacted by this light.
  18871. */
  18872. get: function () {
  18873. return this._excludedMeshes;
  18874. },
  18875. /**
  18876. * Sets the meshes not impacted by this light.
  18877. */
  18878. set: function (value) {
  18879. this._excludedMeshes = value;
  18880. this._hookArrayForExcluded(value);
  18881. },
  18882. enumerable: true,
  18883. configurable: true
  18884. });
  18885. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  18886. /**
  18887. * Gets the layer id use to find what meshes are not impacted by the light.
  18888. * Inactive if 0
  18889. */
  18890. get: function () {
  18891. return this._excludeWithLayerMask;
  18892. },
  18893. /**
  18894. * Sets the layer id use to find what meshes are not impacted by the light.
  18895. * Inactive if 0
  18896. */
  18897. set: function (value) {
  18898. this._excludeWithLayerMask = value;
  18899. this._resyncMeshes();
  18900. },
  18901. enumerable: true,
  18902. configurable: true
  18903. });
  18904. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18905. /**
  18906. * Gets the layer id use to find what meshes are impacted by the light.
  18907. * Inactive if 0
  18908. */
  18909. get: function () {
  18910. return this._includeOnlyWithLayerMask;
  18911. },
  18912. /**
  18913. * Sets the layer id use to find what meshes are impacted by the light.
  18914. * Inactive if 0
  18915. */
  18916. set: function (value) {
  18917. this._includeOnlyWithLayerMask = value;
  18918. this._resyncMeshes();
  18919. },
  18920. enumerable: true,
  18921. configurable: true
  18922. });
  18923. Object.defineProperty(Light.prototype, "lightmapMode", {
  18924. /**
  18925. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18926. */
  18927. get: function () {
  18928. return this._lightmapMode;
  18929. },
  18930. /**
  18931. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18932. */
  18933. set: function (value) {
  18934. if (this._lightmapMode === value) {
  18935. return;
  18936. }
  18937. this._lightmapMode = value;
  18938. this._markMeshesAsLightDirty();
  18939. },
  18940. enumerable: true,
  18941. configurable: true
  18942. });
  18943. /**
  18944. * Returns the string "Light".
  18945. * @returns the class name
  18946. */
  18947. Light.prototype.getClassName = function () {
  18948. return "Light";
  18949. };
  18950. /**
  18951. * Converts the light information to a readable string for debug purpose.
  18952. * @param fullDetails Supports for multiple levels of logging within scene loading
  18953. * @returns the human readable light info
  18954. */
  18955. Light.prototype.toString = function (fullDetails) {
  18956. var ret = "Name: " + this.name;
  18957. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18958. if (this.animations) {
  18959. for (var i = 0; i < this.animations.length; i++) {
  18960. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18961. }
  18962. }
  18963. if (fullDetails) {
  18964. }
  18965. return ret;
  18966. };
  18967. /**
  18968. * Set the enabled state of this node.
  18969. * @param value - the new enabled state
  18970. * @see isEnabled
  18971. */
  18972. Light.prototype.setEnabled = function (value) {
  18973. _super.prototype.setEnabled.call(this, value);
  18974. this._resyncMeshes();
  18975. };
  18976. /**
  18977. * Returns the Light associated shadow generator if any.
  18978. * @return the associated shadow generator.
  18979. */
  18980. Light.prototype.getShadowGenerator = function () {
  18981. return this._shadowGenerator;
  18982. };
  18983. /**
  18984. * Returns a Vector3, the absolute light position in the World.
  18985. * @returns the world space position of the light
  18986. */
  18987. Light.prototype.getAbsolutePosition = function () {
  18988. return BABYLON.Vector3.Zero();
  18989. };
  18990. /**
  18991. * Specifies if the light will affect the passed mesh.
  18992. * @param mesh The mesh to test against the light
  18993. * @return true the mesh is affected otherwise, false.
  18994. */
  18995. Light.prototype.canAffectMesh = function (mesh) {
  18996. if (!mesh) {
  18997. return true;
  18998. }
  18999. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19000. return false;
  19001. }
  19002. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19003. return false;
  19004. }
  19005. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19006. return false;
  19007. }
  19008. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19009. return false;
  19010. }
  19011. return true;
  19012. };
  19013. /**
  19014. * Computes and Returns the light World matrix.
  19015. * @returns the world matrix
  19016. */
  19017. Light.prototype.getWorldMatrix = function () {
  19018. this._currentRenderId = this.getScene().getRenderId();
  19019. var worldMatrix = this._getWorldMatrix();
  19020. if (this.parent && this.parent.getWorldMatrix) {
  19021. if (!this._parentedWorldMatrix) {
  19022. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19023. }
  19024. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19025. this._markSyncedWithParent();
  19026. return this._parentedWorldMatrix;
  19027. }
  19028. return worldMatrix;
  19029. };
  19030. /**
  19031. * Sort function to order lights for rendering.
  19032. * @param a First Light object to compare to second.
  19033. * @param b Second Light object to compare first.
  19034. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19035. */
  19036. Light.CompareLightsPriority = function (a, b) {
  19037. //shadow-casting lights have priority over non-shadow-casting lights
  19038. //the renderPrioirty is a secondary sort criterion
  19039. if (a.shadowEnabled !== b.shadowEnabled) {
  19040. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19041. }
  19042. return b.renderPriority - a.renderPriority;
  19043. };
  19044. /**
  19045. * Disposes the light.
  19046. */
  19047. Light.prototype.dispose = function () {
  19048. if (this._shadowGenerator) {
  19049. this._shadowGenerator.dispose();
  19050. this._shadowGenerator = null;
  19051. }
  19052. // Animations
  19053. this.getScene().stopAnimation(this);
  19054. // Remove from meshes
  19055. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19056. var mesh = _a[_i];
  19057. mesh._removeLightSource(this);
  19058. }
  19059. this._uniformBuffer.dispose();
  19060. // Remove from scene
  19061. this.getScene().removeLight(this);
  19062. _super.prototype.dispose.call(this);
  19063. };
  19064. /**
  19065. * Returns the light type ID (integer).
  19066. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19067. */
  19068. Light.prototype.getTypeID = function () {
  19069. return 0;
  19070. };
  19071. /**
  19072. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19073. * @returns the scaled intensity in intensity mode unit
  19074. */
  19075. Light.prototype.getScaledIntensity = function () {
  19076. return this._photometricScale * this.intensity;
  19077. };
  19078. /**
  19079. * Returns a new Light object, named "name", from the current one.
  19080. * @param name The name of the cloned light
  19081. * @returns the new created light
  19082. */
  19083. Light.prototype.clone = function (name) {
  19084. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19085. if (!constructor) {
  19086. return null;
  19087. }
  19088. return BABYLON.SerializationHelper.Clone(constructor, this);
  19089. };
  19090. /**
  19091. * Serializes the current light into a Serialization object.
  19092. * @returns the serialized object.
  19093. */
  19094. Light.prototype.serialize = function () {
  19095. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19096. // Type
  19097. serializationObject.type = this.getTypeID();
  19098. // Parent
  19099. if (this.parent) {
  19100. serializationObject.parentId = this.parent.id;
  19101. }
  19102. // Inclusion / exclusions
  19103. if (this.excludedMeshes.length > 0) {
  19104. serializationObject.excludedMeshesIds = [];
  19105. this.excludedMeshes.forEach(function (mesh) {
  19106. serializationObject.excludedMeshesIds.push(mesh.id);
  19107. });
  19108. }
  19109. if (this.includedOnlyMeshes.length > 0) {
  19110. serializationObject.includedOnlyMeshesIds = [];
  19111. this.includedOnlyMeshes.forEach(function (mesh) {
  19112. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19113. });
  19114. }
  19115. // Animations
  19116. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19117. serializationObject.ranges = this.serializeAnimationRanges();
  19118. return serializationObject;
  19119. };
  19120. /**
  19121. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19122. * This new light is named "name" and added to the passed scene.
  19123. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19124. * @param name The friendly name of the light
  19125. * @param scene The scene the new light will belong to
  19126. * @returns the constructor function
  19127. */
  19128. Light.GetConstructorFromName = function (type, name, scene) {
  19129. switch (type) {
  19130. case 0:
  19131. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19132. case 1:
  19133. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19134. case 2:
  19135. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19136. case 3:
  19137. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19138. }
  19139. return null;
  19140. };
  19141. /**
  19142. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19143. * @param parsedLight The JSON representation of the light
  19144. * @param scene The scene to create the parsed light in
  19145. * @returns the created light after parsing
  19146. */
  19147. Light.Parse = function (parsedLight, scene) {
  19148. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19149. if (!constructor) {
  19150. return null;
  19151. }
  19152. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19153. // Inclusion / exclusions
  19154. if (parsedLight.excludedMeshesIds) {
  19155. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19156. }
  19157. if (parsedLight.includedOnlyMeshesIds) {
  19158. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19159. }
  19160. // Parent
  19161. if (parsedLight.parentId) {
  19162. light._waitingParentId = parsedLight.parentId;
  19163. }
  19164. // Animations
  19165. if (parsedLight.animations) {
  19166. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19167. var parsedAnimation = parsedLight.animations[animationIndex];
  19168. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19169. }
  19170. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19171. }
  19172. if (parsedLight.autoAnimate) {
  19173. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19174. }
  19175. return light;
  19176. };
  19177. Light.prototype._hookArrayForExcluded = function (array) {
  19178. var _this = this;
  19179. var oldPush = array.push;
  19180. array.push = function () {
  19181. var items = [];
  19182. for (var _i = 0; _i < arguments.length; _i++) {
  19183. items[_i] = arguments[_i];
  19184. }
  19185. var result = oldPush.apply(array, items);
  19186. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19187. var item = items_1[_a];
  19188. item._resyncLighSource(_this);
  19189. }
  19190. return result;
  19191. };
  19192. var oldSplice = array.splice;
  19193. array.splice = function (index, deleteCount) {
  19194. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19195. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19196. var item = deleted_1[_i];
  19197. item._resyncLighSource(_this);
  19198. }
  19199. return deleted;
  19200. };
  19201. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19202. var item = array_1[_i];
  19203. item._resyncLighSource(this);
  19204. }
  19205. };
  19206. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19207. var _this = this;
  19208. var oldPush = array.push;
  19209. array.push = function () {
  19210. var items = [];
  19211. for (var _i = 0; _i < arguments.length; _i++) {
  19212. items[_i] = arguments[_i];
  19213. }
  19214. var result = oldPush.apply(array, items);
  19215. _this._resyncMeshes();
  19216. return result;
  19217. };
  19218. var oldSplice = array.splice;
  19219. array.splice = function (index, deleteCount) {
  19220. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19221. _this._resyncMeshes();
  19222. return deleted;
  19223. };
  19224. this._resyncMeshes();
  19225. };
  19226. Light.prototype._resyncMeshes = function () {
  19227. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19228. var mesh = _a[_i];
  19229. mesh._resyncLighSource(this);
  19230. }
  19231. };
  19232. /**
  19233. * Forces the meshes to update their light related information in their rendering used effects
  19234. * @ignore Internal Use Only
  19235. */
  19236. Light.prototype._markMeshesAsLightDirty = function () {
  19237. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19238. var mesh = _a[_i];
  19239. if (mesh._lightSources.indexOf(this) !== -1) {
  19240. mesh._markSubMeshesAsLightDirty();
  19241. }
  19242. }
  19243. };
  19244. /**
  19245. * Recomputes the cached photometric scale if needed.
  19246. */
  19247. Light.prototype._computePhotometricScale = function () {
  19248. this._photometricScale = this._getPhotometricScale();
  19249. this.getScene().resetCachedMaterial();
  19250. };
  19251. /**
  19252. * Returns the Photometric Scale according to the light type and intensity mode.
  19253. */
  19254. Light.prototype._getPhotometricScale = function () {
  19255. var photometricScale = 0.0;
  19256. var lightTypeID = this.getTypeID();
  19257. //get photometric mode
  19258. var photometricMode = this.intensityMode;
  19259. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19260. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19261. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19262. }
  19263. else {
  19264. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19265. }
  19266. }
  19267. //compute photometric scale
  19268. switch (lightTypeID) {
  19269. case Light.LIGHTTYPEID_POINTLIGHT:
  19270. case Light.LIGHTTYPEID_SPOTLIGHT:
  19271. switch (photometricMode) {
  19272. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19273. photometricScale = 1.0 / (4.0 * Math.PI);
  19274. break;
  19275. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19276. photometricScale = 1.0;
  19277. break;
  19278. case Light.INTENSITYMODE_LUMINANCE:
  19279. photometricScale = this.radius * this.radius;
  19280. break;
  19281. }
  19282. break;
  19283. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19284. switch (photometricMode) {
  19285. case Light.INTENSITYMODE_ILLUMINANCE:
  19286. photometricScale = 1.0;
  19287. break;
  19288. case Light.INTENSITYMODE_LUMINANCE:
  19289. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19290. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19291. var apexAngleRadians = this.radius;
  19292. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19293. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19294. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19295. photometricScale = solidAngle;
  19296. break;
  19297. }
  19298. break;
  19299. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19300. // No fall off in hemisperic light.
  19301. photometricScale = 1.0;
  19302. break;
  19303. }
  19304. return photometricScale;
  19305. };
  19306. /**
  19307. * Reorder the light in the scene according to their defined priority.
  19308. * @ignore Internal Use Only
  19309. */
  19310. Light.prototype._reorderLightsInScene = function () {
  19311. var scene = this.getScene();
  19312. if (this._renderPriority != 0) {
  19313. scene.requireLightSorting = true;
  19314. }
  19315. this.getScene().sortLightsByPriority();
  19316. };
  19317. //lightmapMode Consts
  19318. Light._LIGHTMAP_DEFAULT = 0;
  19319. Light._LIGHTMAP_SPECULAR = 1;
  19320. Light._LIGHTMAP_SHADOWSONLY = 2;
  19321. // Intensity Mode Consts
  19322. Light._INTENSITYMODE_AUTOMATIC = 0;
  19323. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19324. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19325. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19326. Light._INTENSITYMODE_LUMINANCE = 4;
  19327. // Light types ids const.
  19328. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19329. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19330. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19331. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19332. __decorate([
  19333. BABYLON.serializeAsColor3()
  19334. ], Light.prototype, "diffuse", void 0);
  19335. __decorate([
  19336. BABYLON.serializeAsColor3()
  19337. ], Light.prototype, "specular", void 0);
  19338. __decorate([
  19339. BABYLON.serialize()
  19340. ], Light.prototype, "intensity", void 0);
  19341. __decorate([
  19342. BABYLON.serialize()
  19343. ], Light.prototype, "range", void 0);
  19344. __decorate([
  19345. BABYLON.serialize()
  19346. ], Light.prototype, "intensityMode", null);
  19347. __decorate([
  19348. BABYLON.serialize()
  19349. ], Light.prototype, "radius", null);
  19350. __decorate([
  19351. BABYLON.serialize()
  19352. ], Light.prototype, "_renderPriority", void 0);
  19353. __decorate([
  19354. BABYLON.expandToProperty("_reorderLightsInScene")
  19355. ], Light.prototype, "renderPriority", void 0);
  19356. __decorate([
  19357. BABYLON.serialize()
  19358. ], Light.prototype, "shadowEnabled", void 0);
  19359. __decorate([
  19360. BABYLON.serialize("excludeWithLayerMask")
  19361. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19362. __decorate([
  19363. BABYLON.serialize("includeOnlyWithLayerMask")
  19364. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19365. __decorate([
  19366. BABYLON.serialize("lightmapMode")
  19367. ], Light.prototype, "_lightmapMode", void 0);
  19368. return Light;
  19369. }(BABYLON.Node));
  19370. BABYLON.Light = Light;
  19371. })(BABYLON || (BABYLON = {}));
  19372. //# sourceMappingURL=babylon.light.js.map
  19373. var BABYLON;
  19374. (function (BABYLON) {
  19375. var Camera = /** @class */ (function (_super) {
  19376. __extends(Camera, _super);
  19377. function Camera(name, position, scene) {
  19378. var _this = _super.call(this, name, scene) || this;
  19379. /**
  19380. * The vector the camera should consider as up.
  19381. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19382. */
  19383. _this.upVector = BABYLON.Vector3.Up();
  19384. _this.orthoLeft = null;
  19385. _this.orthoRight = null;
  19386. _this.orthoBottom = null;
  19387. _this.orthoTop = null;
  19388. /**
  19389. * FOV is set in Radians. (default is 0.8)
  19390. */
  19391. _this.fov = 0.8;
  19392. _this.minZ = 1;
  19393. _this.maxZ = 10000.0;
  19394. _this.inertia = 0.9;
  19395. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19396. _this.isIntermediate = false;
  19397. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19398. /**
  19399. * Restricts the camera to viewing objects with the same layerMask.
  19400. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19401. */
  19402. _this.layerMask = 0x0FFFFFFF;
  19403. /**
  19404. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19405. */
  19406. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19407. // Camera rig members
  19408. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19409. _this._rigCameras = new Array();
  19410. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19411. _this._skipRendering = false;
  19412. _this.customRenderTargets = new Array();
  19413. // Observables
  19414. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19415. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19416. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19417. _this.onRestoreStateObservable = new BABYLON.Observable();
  19418. // Cache
  19419. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19420. _this._projectionMatrix = new BABYLON.Matrix();
  19421. _this._doNotComputeProjectionMatrix = false;
  19422. _this._postProcesses = new Array();
  19423. _this._transformMatrix = BABYLON.Matrix.Zero();
  19424. _this._activeMeshes = new BABYLON.SmartArray(256);
  19425. _this._globalPosition = BABYLON.Vector3.Zero();
  19426. _this._refreshFrustumPlanes = true;
  19427. _this.getScene().addCamera(_this);
  19428. if (!_this.getScene().activeCamera) {
  19429. _this.getScene().activeCamera = _this;
  19430. }
  19431. _this.position = position;
  19432. return _this;
  19433. }
  19434. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19435. get: function () {
  19436. return Camera._PERSPECTIVE_CAMERA;
  19437. },
  19438. enumerable: true,
  19439. configurable: true
  19440. });
  19441. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19442. get: function () {
  19443. return Camera._ORTHOGRAPHIC_CAMERA;
  19444. },
  19445. enumerable: true,
  19446. configurable: true
  19447. });
  19448. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19449. /**
  19450. * This is the default FOV mode for perspective cameras.
  19451. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19452. *
  19453. */
  19454. get: function () {
  19455. return Camera._FOVMODE_VERTICAL_FIXED;
  19456. },
  19457. enumerable: true,
  19458. configurable: true
  19459. });
  19460. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19461. /**
  19462. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19463. *
  19464. */
  19465. get: function () {
  19466. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19467. },
  19468. enumerable: true,
  19469. configurable: true
  19470. });
  19471. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19472. get: function () {
  19473. return Camera._RIG_MODE_NONE;
  19474. },
  19475. enumerable: true,
  19476. configurable: true
  19477. });
  19478. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19479. get: function () {
  19480. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19481. },
  19482. enumerable: true,
  19483. configurable: true
  19484. });
  19485. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19486. get: function () {
  19487. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19488. },
  19489. enumerable: true,
  19490. configurable: true
  19491. });
  19492. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19493. get: function () {
  19494. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19495. },
  19496. enumerable: true,
  19497. configurable: true
  19498. });
  19499. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19500. get: function () {
  19501. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19502. },
  19503. enumerable: true,
  19504. configurable: true
  19505. });
  19506. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19507. get: function () {
  19508. return Camera._RIG_MODE_VR;
  19509. },
  19510. enumerable: true,
  19511. configurable: true
  19512. });
  19513. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19514. get: function () {
  19515. return Camera._RIG_MODE_WEBVR;
  19516. },
  19517. enumerable: true,
  19518. configurable: true
  19519. });
  19520. /**
  19521. * Store current camera state (fov, position, etc..)
  19522. */
  19523. Camera.prototype.storeState = function () {
  19524. this._stateStored = true;
  19525. this._storedFov = this.fov;
  19526. return this;
  19527. };
  19528. /**
  19529. * Restores the camera state values if it has been stored. You must call storeState() first
  19530. */
  19531. Camera.prototype._restoreStateValues = function () {
  19532. if (!this._stateStored) {
  19533. return false;
  19534. }
  19535. this.fov = this._storedFov;
  19536. return true;
  19537. };
  19538. /**
  19539. * Restored camera state. You must call storeState() first
  19540. */
  19541. Camera.prototype.restoreState = function () {
  19542. if (this._restoreStateValues()) {
  19543. this.onRestoreStateObservable.notifyObservers(this);
  19544. return true;
  19545. }
  19546. return false;
  19547. };
  19548. Camera.prototype.getClassName = function () {
  19549. return "Camera";
  19550. };
  19551. /**
  19552. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19553. */
  19554. Camera.prototype.toString = function (fullDetails) {
  19555. var ret = "Name: " + this.name;
  19556. ret += ", type: " + this.getClassName();
  19557. if (this.animations) {
  19558. for (var i = 0; i < this.animations.length; i++) {
  19559. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19560. }
  19561. }
  19562. if (fullDetails) {
  19563. }
  19564. return ret;
  19565. };
  19566. Object.defineProperty(Camera.prototype, "globalPosition", {
  19567. get: function () {
  19568. return this._globalPosition;
  19569. },
  19570. enumerable: true,
  19571. configurable: true
  19572. });
  19573. Camera.prototype.getActiveMeshes = function () {
  19574. return this._activeMeshes;
  19575. };
  19576. Camera.prototype.isActiveMesh = function (mesh) {
  19577. return (this._activeMeshes.indexOf(mesh) !== -1);
  19578. };
  19579. //Cache
  19580. Camera.prototype._initCache = function () {
  19581. _super.prototype._initCache.call(this);
  19582. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19583. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19584. this._cache.mode = undefined;
  19585. this._cache.minZ = undefined;
  19586. this._cache.maxZ = undefined;
  19587. this._cache.fov = undefined;
  19588. this._cache.fovMode = undefined;
  19589. this._cache.aspectRatio = undefined;
  19590. this._cache.orthoLeft = undefined;
  19591. this._cache.orthoRight = undefined;
  19592. this._cache.orthoBottom = undefined;
  19593. this._cache.orthoTop = undefined;
  19594. this._cache.renderWidth = undefined;
  19595. this._cache.renderHeight = undefined;
  19596. };
  19597. Camera.prototype._updateCache = function (ignoreParentClass) {
  19598. if (!ignoreParentClass) {
  19599. _super.prototype._updateCache.call(this);
  19600. }
  19601. this._cache.position.copyFrom(this.position);
  19602. this._cache.upVector.copyFrom(this.upVector);
  19603. };
  19604. // Synchronized
  19605. Camera.prototype._isSynchronized = function () {
  19606. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19607. };
  19608. Camera.prototype._isSynchronizedViewMatrix = function () {
  19609. if (!_super.prototype._isSynchronized.call(this))
  19610. return false;
  19611. return this._cache.position.equals(this.position)
  19612. && this._cache.upVector.equals(this.upVector)
  19613. && this.isSynchronizedWithParent();
  19614. };
  19615. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19616. var check = this._cache.mode === this.mode
  19617. && this._cache.minZ === this.minZ
  19618. && this._cache.maxZ === this.maxZ;
  19619. if (!check) {
  19620. return false;
  19621. }
  19622. var engine = this.getEngine();
  19623. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19624. check = this._cache.fov === this.fov
  19625. && this._cache.fovMode === this.fovMode
  19626. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19627. }
  19628. else {
  19629. check = this._cache.orthoLeft === this.orthoLeft
  19630. && this._cache.orthoRight === this.orthoRight
  19631. && this._cache.orthoBottom === this.orthoBottom
  19632. && this._cache.orthoTop === this.orthoTop
  19633. && this._cache.renderWidth === engine.getRenderWidth()
  19634. && this._cache.renderHeight === engine.getRenderHeight();
  19635. }
  19636. return check;
  19637. };
  19638. // Controls
  19639. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19640. };
  19641. Camera.prototype.detachControl = function (element) {
  19642. };
  19643. Camera.prototype.update = function () {
  19644. this._checkInputs();
  19645. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19646. this._updateRigCameras();
  19647. }
  19648. };
  19649. Camera.prototype._checkInputs = function () {
  19650. this.onAfterCheckInputsObservable.notifyObservers(this);
  19651. };
  19652. Object.defineProperty(Camera.prototype, "rigCameras", {
  19653. get: function () {
  19654. return this._rigCameras;
  19655. },
  19656. enumerable: true,
  19657. configurable: true
  19658. });
  19659. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19660. get: function () {
  19661. return this._rigPostProcess;
  19662. },
  19663. enumerable: true,
  19664. configurable: true
  19665. });
  19666. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19667. // invalidate framebuffer
  19668. if (this._postProcesses.length > 0) {
  19669. this._postProcesses[0].markTextureDirty();
  19670. }
  19671. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19672. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19673. var cam = this._rigCameras[i];
  19674. var rigPostProcess = cam._rigPostProcess;
  19675. // for VR rig, there does not have to be a post process
  19676. if (rigPostProcess) {
  19677. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19678. if (isPass) {
  19679. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19680. cam.isIntermediate = this._postProcesses.length === 0;
  19681. }
  19682. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19683. rigPostProcess.markTextureDirty();
  19684. }
  19685. else {
  19686. cam._postProcesses = this._postProcesses.slice(0);
  19687. }
  19688. }
  19689. };
  19690. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19691. if (insertAt === void 0) { insertAt = null; }
  19692. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19693. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19694. return 0;
  19695. }
  19696. if (insertAt == null || insertAt < 0) {
  19697. this._postProcesses.push(postProcess);
  19698. }
  19699. else {
  19700. this._postProcesses.splice(insertAt, 0, postProcess);
  19701. }
  19702. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19703. return this._postProcesses.indexOf(postProcess);
  19704. };
  19705. Camera.prototype.detachPostProcess = function (postProcess) {
  19706. var idx = this._postProcesses.indexOf(postProcess);
  19707. if (idx !== -1) {
  19708. this._postProcesses.splice(idx, 1);
  19709. }
  19710. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19711. };
  19712. Camera.prototype.getWorldMatrix = function () {
  19713. if (!this._worldMatrix) {
  19714. this._worldMatrix = BABYLON.Matrix.Identity();
  19715. }
  19716. var viewMatrix = this.getViewMatrix();
  19717. viewMatrix.invertToRef(this._worldMatrix);
  19718. return this._worldMatrix;
  19719. };
  19720. Camera.prototype._getViewMatrix = function () {
  19721. return BABYLON.Matrix.Identity();
  19722. };
  19723. Camera.prototype.getViewMatrix = function (force) {
  19724. if (!force && this._isSynchronizedViewMatrix()) {
  19725. return this._computedViewMatrix;
  19726. }
  19727. this.updateCache();
  19728. this._computedViewMatrix = this._getViewMatrix();
  19729. this._currentRenderId = this.getScene().getRenderId();
  19730. this._refreshFrustumPlanes = true;
  19731. if (!this.parent || !this.parent.getWorldMatrix) {
  19732. this._globalPosition.copyFrom(this.position);
  19733. }
  19734. else {
  19735. if (!this._worldMatrix) {
  19736. this._worldMatrix = BABYLON.Matrix.Identity();
  19737. }
  19738. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19739. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19740. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19741. this._computedViewMatrix.invert();
  19742. this._markSyncedWithParent();
  19743. }
  19744. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  19745. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  19746. }
  19747. this.onViewMatrixChangedObservable.notifyObservers(this);
  19748. return this._computedViewMatrix;
  19749. };
  19750. Camera.prototype.freezeProjectionMatrix = function (projection) {
  19751. this._doNotComputeProjectionMatrix = true;
  19752. if (projection !== undefined) {
  19753. this._projectionMatrix = projection;
  19754. }
  19755. };
  19756. ;
  19757. Camera.prototype.unfreezeProjectionMatrix = function () {
  19758. this._doNotComputeProjectionMatrix = false;
  19759. };
  19760. ;
  19761. Camera.prototype.getProjectionMatrix = function (force) {
  19762. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  19763. return this._projectionMatrix;
  19764. }
  19765. // Cache
  19766. this._cache.mode = this.mode;
  19767. this._cache.minZ = this.minZ;
  19768. this._cache.maxZ = this.maxZ;
  19769. // Matrix
  19770. this._refreshFrustumPlanes = true;
  19771. var engine = this.getEngine();
  19772. var scene = this.getScene();
  19773. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19774. this._cache.fov = this.fov;
  19775. this._cache.fovMode = this.fovMode;
  19776. this._cache.aspectRatio = engine.getAspectRatio(this);
  19777. if (this.minZ <= 0) {
  19778. this.minZ = 0.1;
  19779. }
  19780. if (scene.useRightHandedSystem) {
  19781. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19782. }
  19783. else {
  19784. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19785. }
  19786. }
  19787. else {
  19788. var halfWidth = engine.getRenderWidth() / 2.0;
  19789. var halfHeight = engine.getRenderHeight() / 2.0;
  19790. if (scene.useRightHandedSystem) {
  19791. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19792. }
  19793. else {
  19794. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19795. }
  19796. this._cache.orthoLeft = this.orthoLeft;
  19797. this._cache.orthoRight = this.orthoRight;
  19798. this._cache.orthoBottom = this.orthoBottom;
  19799. this._cache.orthoTop = this.orthoTop;
  19800. this._cache.renderWidth = engine.getRenderWidth();
  19801. this._cache.renderHeight = engine.getRenderHeight();
  19802. }
  19803. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  19804. return this._projectionMatrix;
  19805. };
  19806. Camera.prototype.getTranformationMatrix = function () {
  19807. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19808. return this._transformMatrix;
  19809. };
  19810. Camera.prototype.updateFrustumPlanes = function () {
  19811. if (!this._refreshFrustumPlanes) {
  19812. return;
  19813. }
  19814. this.getTranformationMatrix();
  19815. if (!this._frustumPlanes) {
  19816. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19817. }
  19818. else {
  19819. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19820. }
  19821. this._refreshFrustumPlanes = false;
  19822. };
  19823. Camera.prototype.isInFrustum = function (target) {
  19824. this.updateFrustumPlanes();
  19825. return target.isInFrustum(this._frustumPlanes);
  19826. };
  19827. Camera.prototype.isCompletelyInFrustum = function (target) {
  19828. this.updateFrustumPlanes();
  19829. return target.isCompletelyInFrustum(this._frustumPlanes);
  19830. };
  19831. Camera.prototype.getForwardRay = function (length, transform, origin) {
  19832. if (length === void 0) { length = 100; }
  19833. if (!transform) {
  19834. transform = this.getWorldMatrix();
  19835. }
  19836. if (!origin) {
  19837. origin = this.position;
  19838. }
  19839. var forward = new BABYLON.Vector3(0, 0, 1);
  19840. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  19841. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  19842. return new BABYLON.Ray(origin, direction, length);
  19843. };
  19844. Camera.prototype.dispose = function () {
  19845. // Observables
  19846. this.onViewMatrixChangedObservable.clear();
  19847. this.onProjectionMatrixChangedObservable.clear();
  19848. this.onAfterCheckInputsObservable.clear();
  19849. this.onRestoreStateObservable.clear();
  19850. // Inputs
  19851. if (this.inputs) {
  19852. this.inputs.clear();
  19853. }
  19854. // Animations
  19855. this.getScene().stopAnimation(this);
  19856. // Remove from scene
  19857. this.getScene().removeCamera(this);
  19858. while (this._rigCameras.length > 0) {
  19859. var camera = this._rigCameras.pop();
  19860. if (camera) {
  19861. camera.dispose();
  19862. }
  19863. }
  19864. // Postprocesses
  19865. if (this._rigPostProcess) {
  19866. this._rigPostProcess.dispose(this);
  19867. this._rigPostProcess = null;
  19868. this._postProcesses = [];
  19869. }
  19870. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19871. this._rigPostProcess = null;
  19872. this._postProcesses = [];
  19873. }
  19874. else {
  19875. var i = this._postProcesses.length;
  19876. while (--i >= 0) {
  19877. this._postProcesses[i].dispose(this);
  19878. }
  19879. }
  19880. // Render targets
  19881. var i = this.customRenderTargets.length;
  19882. while (--i >= 0) {
  19883. this.customRenderTargets[i].dispose();
  19884. }
  19885. this.customRenderTargets = [];
  19886. // Active Meshes
  19887. this._activeMeshes.dispose();
  19888. _super.prototype.dispose.call(this);
  19889. };
  19890. Object.defineProperty(Camera.prototype, "leftCamera", {
  19891. // ---- Camera rigs section ----
  19892. get: function () {
  19893. if (this._rigCameras.length < 1) {
  19894. return null;
  19895. }
  19896. return this._rigCameras[0];
  19897. },
  19898. enumerable: true,
  19899. configurable: true
  19900. });
  19901. Object.defineProperty(Camera.prototype, "rightCamera", {
  19902. get: function () {
  19903. if (this._rigCameras.length < 2) {
  19904. return null;
  19905. }
  19906. return this._rigCameras[1];
  19907. },
  19908. enumerable: true,
  19909. configurable: true
  19910. });
  19911. Camera.prototype.getLeftTarget = function () {
  19912. if (this._rigCameras.length < 1) {
  19913. return null;
  19914. }
  19915. return this._rigCameras[0].getTarget();
  19916. };
  19917. Camera.prototype.getRightTarget = function () {
  19918. if (this._rigCameras.length < 2) {
  19919. return null;
  19920. }
  19921. return this._rigCameras[1].getTarget();
  19922. };
  19923. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19924. if (this.cameraRigMode === mode) {
  19925. return;
  19926. }
  19927. while (this._rigCameras.length > 0) {
  19928. var camera = this._rigCameras.pop();
  19929. if (camera) {
  19930. camera.dispose();
  19931. }
  19932. }
  19933. this.cameraRigMode = mode;
  19934. this._cameraRigParams = {};
  19935. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19936. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19937. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19938. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19939. // create the rig cameras, unless none
  19940. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19941. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19942. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19943. if (leftCamera && rightCamera) {
  19944. this._rigCameras.push(leftCamera);
  19945. this._rigCameras.push(rightCamera);
  19946. }
  19947. }
  19948. switch (this.cameraRigMode) {
  19949. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19950. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19951. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19952. break;
  19953. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19954. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19955. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19956. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19957. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19958. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19959. break;
  19960. case Camera.RIG_MODE_VR:
  19961. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19962. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19963. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19964. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19965. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19966. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19967. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19968. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19969. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19970. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19971. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19972. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19973. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19974. if (metrics.compensateDistortion) {
  19975. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19976. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19977. }
  19978. break;
  19979. case Camera.RIG_MODE_WEBVR:
  19980. if (rigParams.vrDisplay) {
  19981. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19982. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19983. //Left eye
  19984. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19985. this._rigCameras[0].setCameraRigParameter("left", true);
  19986. //leaving this for future reference
  19987. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19988. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19989. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19990. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19991. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19992. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19993. this._rigCameras[0].parent = this;
  19994. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19995. //Right eye
  19996. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19997. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19998. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19999. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20000. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20001. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20002. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20003. this._rigCameras[1].parent = this;
  20004. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20005. if (Camera.UseAlternateWebVRRendering) {
  20006. this._rigCameras[1]._skipRendering = true;
  20007. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20008. }
  20009. }
  20010. break;
  20011. }
  20012. this._cascadePostProcessesToRigCams();
  20013. this.update();
  20014. };
  20015. Camera.prototype._getVRProjectionMatrix = function () {
  20016. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20017. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20018. return this._projectionMatrix;
  20019. };
  20020. Camera.prototype._updateCameraRotationMatrix = function () {
  20021. //Here for WebVR
  20022. };
  20023. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20024. //Here for WebVR
  20025. };
  20026. /**
  20027. * This function MUST be overwritten by the different WebVR cameras available.
  20028. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20029. */
  20030. Camera.prototype._getWebVRProjectionMatrix = function () {
  20031. return BABYLON.Matrix.Identity();
  20032. };
  20033. /**
  20034. * This function MUST be overwritten by the different WebVR cameras available.
  20035. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20036. */
  20037. Camera.prototype._getWebVRViewMatrix = function () {
  20038. return BABYLON.Matrix.Identity();
  20039. };
  20040. Camera.prototype.setCameraRigParameter = function (name, value) {
  20041. if (!this._cameraRigParams) {
  20042. this._cameraRigParams = {};
  20043. }
  20044. this._cameraRigParams[name] = value;
  20045. //provisionnally:
  20046. if (name === "interaxialDistance") {
  20047. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20048. }
  20049. };
  20050. /**
  20051. * needs to be overridden by children so sub has required properties to be copied
  20052. */
  20053. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20054. return null;
  20055. };
  20056. /**
  20057. * May need to be overridden by children
  20058. */
  20059. Camera.prototype._updateRigCameras = function () {
  20060. for (var i = 0; i < this._rigCameras.length; i++) {
  20061. this._rigCameras[i].minZ = this.minZ;
  20062. this._rigCameras[i].maxZ = this.maxZ;
  20063. this._rigCameras[i].fov = this.fov;
  20064. }
  20065. // only update viewport when ANAGLYPH
  20066. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20067. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20068. }
  20069. };
  20070. Camera.prototype._setupInputs = function () {
  20071. };
  20072. Camera.prototype.serialize = function () {
  20073. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20074. // Type
  20075. serializationObject.type = this.getClassName();
  20076. // Parent
  20077. if (this.parent) {
  20078. serializationObject.parentId = this.parent.id;
  20079. }
  20080. if (this.inputs) {
  20081. this.inputs.serialize(serializationObject);
  20082. }
  20083. // Animations
  20084. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20085. serializationObject.ranges = this.serializeAnimationRanges();
  20086. return serializationObject;
  20087. };
  20088. Camera.prototype.clone = function (name) {
  20089. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20090. };
  20091. Camera.prototype.getDirection = function (localAxis) {
  20092. var result = BABYLON.Vector3.Zero();
  20093. this.getDirectionToRef(localAxis, result);
  20094. return result;
  20095. };
  20096. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20097. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20098. };
  20099. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20100. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20101. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20102. switch (type) {
  20103. case "ArcRotateCamera":
  20104. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20105. case "DeviceOrientationCamera":
  20106. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20107. case "FollowCamera":
  20108. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20109. case "ArcFollowCamera":
  20110. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20111. case "GamepadCamera":
  20112. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20113. case "TouchCamera":
  20114. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20115. case "VirtualJoysticksCamera":
  20116. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20117. case "WebVRFreeCamera":
  20118. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20119. case "WebVRGamepadCamera":
  20120. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20121. case "VRDeviceOrientationFreeCamera":
  20122. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20123. case "VRDeviceOrientationGamepadCamera":
  20124. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20125. case "AnaglyphArcRotateCamera":
  20126. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20127. case "AnaglyphFreeCamera":
  20128. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20129. case "AnaglyphGamepadCamera":
  20130. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20131. case "AnaglyphUniversalCamera":
  20132. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20133. case "StereoscopicArcRotateCamera":
  20134. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20135. case "StereoscopicFreeCamera":
  20136. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20137. case "StereoscopicGamepadCamera":
  20138. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20139. case "StereoscopicUniversalCamera":
  20140. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20141. case "FreeCamera":// Forcing Universal here
  20142. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20143. default:// Universal Camera is the default value
  20144. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20145. }
  20146. };
  20147. Camera.prototype.computeWorldMatrix = function () {
  20148. return this.getWorldMatrix();
  20149. };
  20150. Camera.Parse = function (parsedCamera, scene) {
  20151. var type = parsedCamera.type;
  20152. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20153. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20154. // Parent
  20155. if (parsedCamera.parentId) {
  20156. camera._waitingParentId = parsedCamera.parentId;
  20157. }
  20158. //If camera has an input manager, let it parse inputs settings
  20159. if (camera.inputs) {
  20160. camera.inputs.parse(parsedCamera);
  20161. camera._setupInputs();
  20162. }
  20163. if (camera.setPosition) {
  20164. camera.position.copyFromFloats(0, 0, 0);
  20165. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20166. }
  20167. // Target
  20168. if (parsedCamera.target) {
  20169. if (camera.setTarget) {
  20170. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20171. }
  20172. }
  20173. // Apply 3d rig, when found
  20174. if (parsedCamera.cameraRigMode) {
  20175. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20176. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20177. }
  20178. // Animations
  20179. if (parsedCamera.animations) {
  20180. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20181. var parsedAnimation = parsedCamera.animations[animationIndex];
  20182. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20183. }
  20184. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20185. }
  20186. if (parsedCamera.autoAnimate) {
  20187. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20188. }
  20189. return camera;
  20190. };
  20191. // Statics
  20192. Camera._PERSPECTIVE_CAMERA = 0;
  20193. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20194. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20195. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20196. Camera._RIG_MODE_NONE = 0;
  20197. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20198. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20199. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20200. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20201. Camera._RIG_MODE_VR = 20;
  20202. Camera._RIG_MODE_WEBVR = 21;
  20203. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20204. Camera.UseAlternateWebVRRendering = false;
  20205. __decorate([
  20206. BABYLON.serializeAsVector3()
  20207. ], Camera.prototype, "position", void 0);
  20208. __decorate([
  20209. BABYLON.serializeAsVector3()
  20210. ], Camera.prototype, "upVector", void 0);
  20211. __decorate([
  20212. BABYLON.serialize()
  20213. ], Camera.prototype, "orthoLeft", void 0);
  20214. __decorate([
  20215. BABYLON.serialize()
  20216. ], Camera.prototype, "orthoRight", void 0);
  20217. __decorate([
  20218. BABYLON.serialize()
  20219. ], Camera.prototype, "orthoBottom", void 0);
  20220. __decorate([
  20221. BABYLON.serialize()
  20222. ], Camera.prototype, "orthoTop", void 0);
  20223. __decorate([
  20224. BABYLON.serialize()
  20225. ], Camera.prototype, "fov", void 0);
  20226. __decorate([
  20227. BABYLON.serialize()
  20228. ], Camera.prototype, "minZ", void 0);
  20229. __decorate([
  20230. BABYLON.serialize()
  20231. ], Camera.prototype, "maxZ", void 0);
  20232. __decorate([
  20233. BABYLON.serialize()
  20234. ], Camera.prototype, "inertia", void 0);
  20235. __decorate([
  20236. BABYLON.serialize()
  20237. ], Camera.prototype, "mode", void 0);
  20238. __decorate([
  20239. BABYLON.serialize()
  20240. ], Camera.prototype, "layerMask", void 0);
  20241. __decorate([
  20242. BABYLON.serialize()
  20243. ], Camera.prototype, "fovMode", void 0);
  20244. __decorate([
  20245. BABYLON.serialize()
  20246. ], Camera.prototype, "cameraRigMode", void 0);
  20247. __decorate([
  20248. BABYLON.serialize()
  20249. ], Camera.prototype, "interaxialDistance", void 0);
  20250. __decorate([
  20251. BABYLON.serialize()
  20252. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20253. return Camera;
  20254. }(BABYLON.Node));
  20255. BABYLON.Camera = Camera;
  20256. })(BABYLON || (BABYLON = {}));
  20257. //# sourceMappingURL=babylon.camera.js.map
  20258. var BABYLON;
  20259. (function (BABYLON) {
  20260. var RenderingManager = /** @class */ (function () {
  20261. function RenderingManager(scene) {
  20262. this._renderingGroups = new Array();
  20263. this._autoClearDepthStencil = {};
  20264. this._customOpaqueSortCompareFn = {};
  20265. this._customAlphaTestSortCompareFn = {};
  20266. this._customTransparentSortCompareFn = {};
  20267. this._renderinGroupInfo = null;
  20268. this._scene = scene;
  20269. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20270. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20271. }
  20272. }
  20273. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20274. if (depth === void 0) { depth = true; }
  20275. if (stencil === void 0) { stencil = true; }
  20276. if (this._depthStencilBufferAlreadyCleaned) {
  20277. return;
  20278. }
  20279. this._scene.getEngine().clear(null, false, depth, stencil);
  20280. this._depthStencilBufferAlreadyCleaned = true;
  20281. };
  20282. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20283. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20284. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20285. var info = null;
  20286. if (observable) {
  20287. if (!this._renderinGroupInfo) {
  20288. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20289. }
  20290. info = this._renderinGroupInfo;
  20291. info.scene = this._scene;
  20292. info.camera = this._scene.activeCamera;
  20293. }
  20294. // Dispatch sprites
  20295. if (renderSprites) {
  20296. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20297. var manager = this._scene.spriteManagers[index];
  20298. this.dispatchSprites(manager);
  20299. }
  20300. }
  20301. // Render
  20302. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20303. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20304. var renderingGroup = this._renderingGroups[index];
  20305. if (!renderingGroup && !observable)
  20306. continue;
  20307. var renderingGroupMask = 0;
  20308. // Fire PRECLEAR stage
  20309. if (observable && info) {
  20310. renderingGroupMask = Math.pow(2, index);
  20311. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20312. info.renderingGroupId = index;
  20313. observable.notifyObservers(info, renderingGroupMask);
  20314. }
  20315. // Clear depth/stencil if needed
  20316. if (RenderingManager.AUTOCLEAR) {
  20317. var autoClear = this._autoClearDepthStencil[index];
  20318. if (autoClear && autoClear.autoClear) {
  20319. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20320. }
  20321. }
  20322. if (observable && info) {
  20323. // Fire PREOPAQUE stage
  20324. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20325. observable.notifyObservers(info, renderingGroupMask);
  20326. // Fire PRETRANSPARENT stage
  20327. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20328. observable.notifyObservers(info, renderingGroupMask);
  20329. }
  20330. if (renderingGroup)
  20331. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20332. // Fire POSTTRANSPARENT stage
  20333. if (observable && info) {
  20334. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20335. observable.notifyObservers(info, renderingGroupMask);
  20336. }
  20337. }
  20338. };
  20339. RenderingManager.prototype.reset = function () {
  20340. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20341. var renderingGroup = this._renderingGroups[index];
  20342. if (renderingGroup) {
  20343. renderingGroup.prepare();
  20344. }
  20345. }
  20346. };
  20347. RenderingManager.prototype.dispose = function () {
  20348. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20349. var renderingGroup = this._renderingGroups[index];
  20350. if (renderingGroup) {
  20351. renderingGroup.dispose();
  20352. }
  20353. }
  20354. this._renderingGroups.length = 0;
  20355. };
  20356. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20357. if (this._renderingGroups[renderingGroupId] === undefined) {
  20358. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20359. }
  20360. };
  20361. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20362. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20363. this._prepareRenderingGroup(renderingGroupId);
  20364. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20365. };
  20366. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20367. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20368. this._prepareRenderingGroup(renderingGroupId);
  20369. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20370. };
  20371. /**
  20372. * @param subMesh The submesh to dispatch
  20373. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20374. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20375. */
  20376. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20377. if (mesh === undefined) {
  20378. mesh = subMesh.getMesh();
  20379. }
  20380. var renderingGroupId = mesh.renderingGroupId || 0;
  20381. this._prepareRenderingGroup(renderingGroupId);
  20382. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20383. };
  20384. /**
  20385. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20386. * This allowed control for front to back rendering or reversly depending of the special needs.
  20387. *
  20388. * @param renderingGroupId The rendering group id corresponding to its index
  20389. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20390. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20391. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20392. */
  20393. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20394. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20395. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20396. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20397. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20398. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20399. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20400. if (this._renderingGroups[renderingGroupId]) {
  20401. var group = this._renderingGroups[renderingGroupId];
  20402. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20403. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20404. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20405. }
  20406. };
  20407. /**
  20408. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20409. *
  20410. * @param renderingGroupId The rendering group id corresponding to its index
  20411. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20412. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20413. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20414. */
  20415. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20416. if (depth === void 0) { depth = true; }
  20417. if (stencil === void 0) { stencil = true; }
  20418. this._autoClearDepthStencil[renderingGroupId] = {
  20419. autoClear: autoClearDepthStencil,
  20420. depth: depth,
  20421. stencil: stencil
  20422. };
  20423. };
  20424. /**
  20425. * The max id used for rendering groups (not included)
  20426. */
  20427. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20428. /**
  20429. * The min id used for rendering groups (included)
  20430. */
  20431. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20432. /**
  20433. * Used to globally prevent autoclearing scenes.
  20434. */
  20435. RenderingManager.AUTOCLEAR = true;
  20436. return RenderingManager;
  20437. }());
  20438. BABYLON.RenderingManager = RenderingManager;
  20439. })(BABYLON || (BABYLON = {}));
  20440. //# sourceMappingURL=babylon.renderingManager.js.map
  20441. var BABYLON;
  20442. (function (BABYLON) {
  20443. var RenderingGroup = /** @class */ (function () {
  20444. /**
  20445. * Creates a new rendering group.
  20446. * @param index The rendering group index
  20447. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20448. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20449. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20450. */
  20451. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20452. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20453. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20454. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20455. this.index = index;
  20456. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20457. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20458. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20459. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20460. this._particleSystems = new BABYLON.SmartArray(256);
  20461. this._spriteManagers = new BABYLON.SmartArray(256);
  20462. this._edgesRenderers = new BABYLON.SmartArray(16);
  20463. this._scene = scene;
  20464. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20465. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20466. this.transparentSortCompareFn = transparentSortCompareFn;
  20467. }
  20468. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20469. /**
  20470. * Set the opaque sort comparison function.
  20471. * If null the sub meshes will be render in the order they were created
  20472. */
  20473. set: function (value) {
  20474. this._opaqueSortCompareFn = value;
  20475. if (value) {
  20476. this._renderOpaque = this.renderOpaqueSorted;
  20477. }
  20478. else {
  20479. this._renderOpaque = RenderingGroup.renderUnsorted;
  20480. }
  20481. },
  20482. enumerable: true,
  20483. configurable: true
  20484. });
  20485. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20486. /**
  20487. * Set the alpha test sort comparison function.
  20488. * If null the sub meshes will be render in the order they were created
  20489. */
  20490. set: function (value) {
  20491. this._alphaTestSortCompareFn = value;
  20492. if (value) {
  20493. this._renderAlphaTest = this.renderAlphaTestSorted;
  20494. }
  20495. else {
  20496. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20497. }
  20498. },
  20499. enumerable: true,
  20500. configurable: true
  20501. });
  20502. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20503. /**
  20504. * Set the transparent sort comparison function.
  20505. * If null the sub meshes will be render in the order they were created
  20506. */
  20507. set: function (value) {
  20508. if (value) {
  20509. this._transparentSortCompareFn = value;
  20510. }
  20511. else {
  20512. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20513. }
  20514. this._renderTransparent = this.renderTransparentSorted;
  20515. },
  20516. enumerable: true,
  20517. configurable: true
  20518. });
  20519. /**
  20520. * Render all the sub meshes contained in the group.
  20521. * @param customRenderFunction Used to override the default render behaviour of the group.
  20522. * @returns true if rendered some submeshes.
  20523. */
  20524. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20525. if (customRenderFunction) {
  20526. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20527. return;
  20528. }
  20529. var engine = this._scene.getEngine();
  20530. // Depth only
  20531. if (this._depthOnlySubMeshes.length !== 0) {
  20532. engine.setColorWrite(false);
  20533. this._renderAlphaTest(this._depthOnlySubMeshes);
  20534. engine.setColorWrite(true);
  20535. }
  20536. // Opaque
  20537. if (this._opaqueSubMeshes.length !== 0) {
  20538. this._renderOpaque(this._opaqueSubMeshes);
  20539. }
  20540. // Alpha test
  20541. if (this._alphaTestSubMeshes.length !== 0) {
  20542. this._renderAlphaTest(this._alphaTestSubMeshes);
  20543. }
  20544. var stencilState = engine.getStencilBuffer();
  20545. engine.setStencilBuffer(false);
  20546. // Sprites
  20547. if (renderSprites) {
  20548. this._renderSprites();
  20549. }
  20550. // Particles
  20551. if (renderParticles) {
  20552. this._renderParticles(activeMeshes);
  20553. }
  20554. if (this.onBeforeTransparentRendering) {
  20555. this.onBeforeTransparentRendering();
  20556. }
  20557. // Transparent
  20558. if (this._transparentSubMeshes.length !== 0) {
  20559. this._renderTransparent(this._transparentSubMeshes);
  20560. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20561. }
  20562. // Set back stencil to false in case it changes before the edge renderer.
  20563. engine.setStencilBuffer(false);
  20564. // Edges
  20565. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20566. this._edgesRenderers.data[edgesRendererIndex].render();
  20567. }
  20568. // Restore Stencil state.
  20569. engine.setStencilBuffer(stencilState);
  20570. };
  20571. /**
  20572. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20573. * @param subMeshes The submeshes to render
  20574. */
  20575. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20576. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20577. };
  20578. /**
  20579. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20580. * @param subMeshes The submeshes to render
  20581. */
  20582. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20583. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20584. };
  20585. /**
  20586. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20587. * @param subMeshes The submeshes to render
  20588. */
  20589. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20590. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20591. };
  20592. /**
  20593. * Renders the submeshes in a specified order.
  20594. * @param subMeshes The submeshes to sort before render
  20595. * @param sortCompareFn The comparison function use to sort
  20596. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20597. * @param transparent Specifies to activate blending if true
  20598. */
  20599. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20600. var subIndex = 0;
  20601. var subMesh;
  20602. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20603. for (; subIndex < subMeshes.length; subIndex++) {
  20604. subMesh = subMeshes.data[subIndex];
  20605. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20606. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20607. }
  20608. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20609. if (sortCompareFn) {
  20610. sortedArray.sort(sortCompareFn);
  20611. }
  20612. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20613. subMesh = sortedArray[subIndex];
  20614. if (transparent) {
  20615. var material = subMesh.getMaterial();
  20616. if (material && material.needDepthPrePass) {
  20617. var engine = material.getScene().getEngine();
  20618. engine.setColorWrite(false);
  20619. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20620. subMesh.render(false);
  20621. engine.setColorWrite(true);
  20622. }
  20623. }
  20624. subMesh.render(transparent);
  20625. }
  20626. };
  20627. /**
  20628. * Renders the submeshes in the order they were dispatched (no sort applied).
  20629. * @param subMeshes The submeshes to render
  20630. */
  20631. RenderingGroup.renderUnsorted = function (subMeshes) {
  20632. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20633. var submesh = subMeshes.data[subIndex];
  20634. submesh.render(false);
  20635. }
  20636. };
  20637. /**
  20638. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20639. * are rendered back to front if in the same alpha index.
  20640. *
  20641. * @param a The first submesh
  20642. * @param b The second submesh
  20643. * @returns The result of the comparison
  20644. */
  20645. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20646. // Alpha index first
  20647. if (a._alphaIndex > b._alphaIndex) {
  20648. return 1;
  20649. }
  20650. if (a._alphaIndex < b._alphaIndex) {
  20651. return -1;
  20652. }
  20653. // Then distance to camera
  20654. return RenderingGroup.backToFrontSortCompare(a, b);
  20655. };
  20656. /**
  20657. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20658. * are rendered back to front.
  20659. *
  20660. * @param a The first submesh
  20661. * @param b The second submesh
  20662. * @returns The result of the comparison
  20663. */
  20664. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20665. // Then distance to camera
  20666. if (a._distanceToCamera < b._distanceToCamera) {
  20667. return 1;
  20668. }
  20669. if (a._distanceToCamera > b._distanceToCamera) {
  20670. return -1;
  20671. }
  20672. return 0;
  20673. };
  20674. /**
  20675. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20676. * are rendered front to back (prevent overdraw).
  20677. *
  20678. * @param a The first submesh
  20679. * @param b The second submesh
  20680. * @returns The result of the comparison
  20681. */
  20682. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20683. // Then distance to camera
  20684. if (a._distanceToCamera < b._distanceToCamera) {
  20685. return -1;
  20686. }
  20687. if (a._distanceToCamera > b._distanceToCamera) {
  20688. return 1;
  20689. }
  20690. return 0;
  20691. };
  20692. /**
  20693. * Resets the different lists of submeshes to prepare a new frame.
  20694. */
  20695. RenderingGroup.prototype.prepare = function () {
  20696. this._opaqueSubMeshes.reset();
  20697. this._transparentSubMeshes.reset();
  20698. this._alphaTestSubMeshes.reset();
  20699. this._depthOnlySubMeshes.reset();
  20700. this._particleSystems.reset();
  20701. this._spriteManagers.reset();
  20702. this._edgesRenderers.reset();
  20703. };
  20704. RenderingGroup.prototype.dispose = function () {
  20705. this._opaqueSubMeshes.dispose();
  20706. this._transparentSubMeshes.dispose();
  20707. this._alphaTestSubMeshes.dispose();
  20708. this._depthOnlySubMeshes.dispose();
  20709. this._particleSystems.dispose();
  20710. this._spriteManagers.dispose();
  20711. this._edgesRenderers.dispose();
  20712. };
  20713. /**
  20714. * Inserts the submesh in its correct queue depending on its material.
  20715. * @param subMesh The submesh to dispatch
  20716. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20717. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20718. */
  20719. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20720. // Get mesh and materials if not provided
  20721. if (mesh === undefined) {
  20722. mesh = subMesh.getMesh();
  20723. }
  20724. if (material === undefined) {
  20725. material = subMesh.getMaterial();
  20726. }
  20727. if (material === null || material === undefined) {
  20728. return;
  20729. }
  20730. if (material.needAlphaBlendingForMesh(mesh)) {
  20731. this._transparentSubMeshes.push(subMesh);
  20732. }
  20733. else if (material.needAlphaTesting()) {
  20734. if (material.needDepthPrePass) {
  20735. this._depthOnlySubMeshes.push(subMesh);
  20736. }
  20737. this._alphaTestSubMeshes.push(subMesh);
  20738. }
  20739. else {
  20740. if (material.needDepthPrePass) {
  20741. this._depthOnlySubMeshes.push(subMesh);
  20742. }
  20743. this._opaqueSubMeshes.push(subMesh); // Opaque
  20744. }
  20745. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  20746. this._edgesRenderers.push(mesh._edgesRenderer);
  20747. }
  20748. };
  20749. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  20750. this._spriteManagers.push(spriteManager);
  20751. };
  20752. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  20753. this._particleSystems.push(particleSystem);
  20754. };
  20755. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  20756. if (this._particleSystems.length === 0) {
  20757. return;
  20758. }
  20759. // Particles
  20760. var activeCamera = this._scene.activeCamera;
  20761. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  20762. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  20763. var particleSystem = this._particleSystems.data[particleIndex];
  20764. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  20765. continue;
  20766. }
  20767. var emitter = particleSystem.emitter;
  20768. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  20769. this._scene._activeParticles.addCount(particleSystem.render(), false);
  20770. }
  20771. }
  20772. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  20773. };
  20774. RenderingGroup.prototype._renderSprites = function () {
  20775. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  20776. return;
  20777. }
  20778. // Sprites
  20779. var activeCamera = this._scene.activeCamera;
  20780. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  20781. for (var id = 0; id < this._spriteManagers.length; id++) {
  20782. var spriteManager = this._spriteManagers.data[id];
  20783. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  20784. spriteManager.render();
  20785. }
  20786. }
  20787. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  20788. };
  20789. return RenderingGroup;
  20790. }());
  20791. BABYLON.RenderingGroup = RenderingGroup;
  20792. })(BABYLON || (BABYLON = {}));
  20793. //# sourceMappingURL=babylon.renderingGroup.js.map
  20794. var BABYLON;
  20795. (function (BABYLON) {
  20796. var ClickInfo = /** @class */ (function () {
  20797. function ClickInfo() {
  20798. this._singleClick = false;
  20799. this._doubleClick = false;
  20800. this._hasSwiped = false;
  20801. this._ignore = false;
  20802. }
  20803. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  20804. get: function () {
  20805. return this._singleClick;
  20806. },
  20807. set: function (b) {
  20808. this._singleClick = b;
  20809. },
  20810. enumerable: true,
  20811. configurable: true
  20812. });
  20813. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  20814. get: function () {
  20815. return this._doubleClick;
  20816. },
  20817. set: function (b) {
  20818. this._doubleClick = b;
  20819. },
  20820. enumerable: true,
  20821. configurable: true
  20822. });
  20823. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  20824. get: function () {
  20825. return this._hasSwiped;
  20826. },
  20827. set: function (b) {
  20828. this._hasSwiped = b;
  20829. },
  20830. enumerable: true,
  20831. configurable: true
  20832. });
  20833. Object.defineProperty(ClickInfo.prototype, "ignore", {
  20834. get: function () {
  20835. return this._ignore;
  20836. },
  20837. set: function (b) {
  20838. this._ignore = b;
  20839. },
  20840. enumerable: true,
  20841. configurable: true
  20842. });
  20843. return ClickInfo;
  20844. }());
  20845. /**
  20846. * This class is used by the onRenderingGroupObservable
  20847. */
  20848. var RenderingGroupInfo = /** @class */ (function () {
  20849. function RenderingGroupInfo() {
  20850. }
  20851. /**
  20852. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  20853. * This stage will be fired no matter what
  20854. */
  20855. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  20856. /**
  20857. * Called before opaque object are rendered.
  20858. * This stage will be fired only if there's 3D Opaque content to render
  20859. */
  20860. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  20861. /**
  20862. * Called after the opaque objects are rendered and before the transparent ones
  20863. * This stage will be fired only if there's 3D transparent content to render
  20864. */
  20865. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  20866. /**
  20867. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  20868. * This stage will be fired no matter what
  20869. */
  20870. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  20871. return RenderingGroupInfo;
  20872. }());
  20873. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  20874. /**
  20875. * Represents a scene to be rendered by the engine.
  20876. * @see http://doc.babylonjs.com/page.php?p=21911
  20877. */
  20878. var Scene = /** @class */ (function () {
  20879. /**
  20880. * @constructor
  20881. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  20882. */
  20883. function Scene(engine) {
  20884. // Members
  20885. this.autoClear = true;
  20886. this.autoClearDepthAndStencil = true;
  20887. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20888. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20889. this.forceWireframe = false;
  20890. this._forcePointsCloud = false;
  20891. this.forceShowBoundingBoxes = false;
  20892. this.animationsEnabled = true;
  20893. this.useConstantAnimationDeltaTime = false;
  20894. this.constantlyUpdateMeshUnderPointer = false;
  20895. this.hoverCursor = "pointer";
  20896. this.defaultCursor = "";
  20897. /**
  20898. * This is used to call preventDefault() on pointer down
  20899. * in order to block unwanted artifacts like system double clicks
  20900. */
  20901. this.preventDefaultOnPointerDown = true;
  20902. // Metadata
  20903. this.metadata = null;
  20904. /**
  20905. * An event triggered when the scene is disposed.
  20906. * @type {BABYLON.Observable}
  20907. */
  20908. this.onDisposeObservable = new BABYLON.Observable();
  20909. /**
  20910. * An event triggered before rendering the scene (right after animations and physics)
  20911. * @type {BABYLON.Observable}
  20912. */
  20913. this.onBeforeRenderObservable = new BABYLON.Observable();
  20914. /**
  20915. * An event triggered after rendering the scene
  20916. * @type {BABYLON.Observable}
  20917. */
  20918. this.onAfterRenderObservable = new BABYLON.Observable();
  20919. /**
  20920. * An event triggered before animating the scene
  20921. * @type {BABYLON.Observable}
  20922. */
  20923. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20924. /**
  20925. * An event triggered after animations processing
  20926. * @type {BABYLON.Observable}
  20927. */
  20928. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20929. /**
  20930. * An event triggered before draw calls are ready to be sent
  20931. * @type {BABYLON.Observable}
  20932. */
  20933. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20934. /**
  20935. * An event triggered after draw calls have been sent
  20936. * @type {BABYLON.Observable}
  20937. */
  20938. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20939. /**
  20940. * An event triggered when physic simulation is about to be run
  20941. * @type {BABYLON.Observable}
  20942. */
  20943. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20944. /**
  20945. * An event triggered when physic simulation has been done
  20946. * @type {BABYLON.Observable}
  20947. */
  20948. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20949. /**
  20950. * An event triggered when the scene is ready
  20951. * @type {BABYLON.Observable}
  20952. */
  20953. this.onReadyObservable = new BABYLON.Observable();
  20954. /**
  20955. * An event triggered before rendering a camera
  20956. * @type {BABYLON.Observable}
  20957. */
  20958. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20959. /**
  20960. * An event triggered after rendering a camera
  20961. * @type {BABYLON.Observable}
  20962. */
  20963. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20964. /**
  20965. * An event triggered when active meshes evaluation is about to start
  20966. * @type {BABYLON.Observable}
  20967. */
  20968. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20969. /**
  20970. * An event triggered when active meshes evaluation is done
  20971. * @type {BABYLON.Observable}
  20972. */
  20973. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20974. /**
  20975. * An event triggered when particles rendering is about to start
  20976. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20977. * @type {BABYLON.Observable}
  20978. */
  20979. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20980. /**
  20981. * An event triggered when particles rendering is done
  20982. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20983. * @type {BABYLON.Observable}
  20984. */
  20985. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20986. /**
  20987. * An event triggered when sprites rendering is about to start
  20988. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20989. * @type {BABYLON.Observable}
  20990. */
  20991. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20992. /**
  20993. * An event triggered when sprites rendering is done
  20994. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20995. * @type {BABYLON.Observable}
  20996. */
  20997. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20998. /**
  20999. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21000. * @type {BABYLON.Observable}
  21001. */
  21002. this.onDataLoadedObservable = new BABYLON.Observable();
  21003. /**
  21004. * An event triggered when a camera is created
  21005. * @type {BABYLON.Observable}
  21006. */
  21007. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21008. /**
  21009. * An event triggered when a camera is removed
  21010. * @type {BABYLON.Observable}
  21011. */
  21012. this.onCameraRemovedObservable = new BABYLON.Observable();
  21013. /**
  21014. * An event triggered when a light is created
  21015. * @type {BABYLON.Observable}
  21016. */
  21017. this.onNewLightAddedObservable = new BABYLON.Observable();
  21018. /**
  21019. * An event triggered when a light is removed
  21020. * @type {BABYLON.Observable}
  21021. */
  21022. this.onLightRemovedObservable = new BABYLON.Observable();
  21023. /**
  21024. * An event triggered when a geometry is created
  21025. * @type {BABYLON.Observable}
  21026. */
  21027. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21028. /**
  21029. * An event triggered when a geometry is removed
  21030. * @type {BABYLON.Observable}
  21031. */
  21032. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21033. /**
  21034. * An event triggered when a transform node is created
  21035. * @type {BABYLON.Observable}
  21036. */
  21037. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21038. /**
  21039. * An event triggered when a transform node is removed
  21040. * @type {BABYLON.Observable}
  21041. */
  21042. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21043. /**
  21044. * An event triggered when a mesh is created
  21045. * @type {BABYLON.Observable}
  21046. */
  21047. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21048. /**
  21049. * An event triggered when a mesh is removed
  21050. * @type {BABYLON.Observable}
  21051. */
  21052. this.onMeshRemovedObservable = new BABYLON.Observable();
  21053. /**
  21054. * An event triggered when render targets are about to be rendered
  21055. * Can happen multiple times per frame.
  21056. * @type {BABYLON.Observable}
  21057. */
  21058. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21059. /**
  21060. * An event triggered when render targets were rendered.
  21061. * Can happen multiple times per frame.
  21062. * @type {BABYLON.Observable}
  21063. */
  21064. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21065. /**
  21066. * An event triggered before calculating deterministic simulation step
  21067. * @type {BABYLON.Observable}
  21068. */
  21069. this.onBeforeStepObservable = new BABYLON.Observable();
  21070. /**
  21071. * An event triggered after calculating deterministic simulation step
  21072. * @type {BABYLON.Observable}
  21073. */
  21074. this.onAfterStepObservable = new BABYLON.Observable();
  21075. /**
  21076. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21077. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21078. * 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)
  21079. */
  21080. this.onRenderingGroupObservable = new BABYLON.Observable();
  21081. // Animations
  21082. this.animations = [];
  21083. /**
  21084. * 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).
  21085. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21086. */
  21087. this.onPrePointerObservable = new BABYLON.Observable();
  21088. /**
  21089. * Observable event triggered each time an input event is received from the rendering canvas
  21090. */
  21091. this.onPointerObservable = new BABYLON.Observable();
  21092. this._meshPickProceed = false;
  21093. this._currentPickResult = null;
  21094. this._previousPickResult = null;
  21095. this._totalPointersPressed = 0;
  21096. this._doubleClickOccured = false;
  21097. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21098. this.cameraToUseForPointers = null;
  21099. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21100. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21101. this._startingPointerTime = 0;
  21102. this._previousStartingPointerTime = 0;
  21103. // Deterministic lockstep
  21104. this._timeAccumulator = 0;
  21105. this._currentStepId = 0;
  21106. this._currentInternalStep = 0;
  21107. // Keyboard
  21108. /**
  21109. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21110. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21111. */
  21112. this.onPreKeyboardObservable = new BABYLON.Observable();
  21113. /**
  21114. * Observable event triggered each time an keyboard event is received from the hosting window
  21115. */
  21116. this.onKeyboardObservable = new BABYLON.Observable();
  21117. // Coordinate system
  21118. /**
  21119. * use right-handed coordinate system on this scene.
  21120. * @type {boolean}
  21121. */
  21122. this._useRightHandedSystem = false;
  21123. // Fog
  21124. this._fogEnabled = true;
  21125. this._fogMode = Scene.FOGMODE_NONE;
  21126. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21127. this.fogDensity = 0.1;
  21128. this.fogStart = 0;
  21129. this.fogEnd = 1000.0;
  21130. // Lights
  21131. /**
  21132. * is shadow enabled on this scene.
  21133. * @type {boolean}
  21134. */
  21135. this._shadowsEnabled = true;
  21136. /**
  21137. * is light enabled on this scene.
  21138. * @type {boolean}
  21139. */
  21140. this._lightsEnabled = true;
  21141. /**
  21142. * All of the lights added to this scene.
  21143. * @see BABYLON.Light
  21144. * @type {BABYLON.Light[]}
  21145. */
  21146. this.lights = new Array();
  21147. // Cameras
  21148. /** All of the cameras added to this scene. */
  21149. this.cameras = new Array();
  21150. /** All of the active cameras added to this scene. */
  21151. this.activeCameras = new Array();
  21152. // Meshes
  21153. /**
  21154. * All of the tranform nodes added to this scene.
  21155. * @see BABYLON.TransformNode
  21156. * @type {BABYLON.TransformNode[]}
  21157. */
  21158. this.transformNodes = new Array();
  21159. /**
  21160. * All of the (abstract) meshes added to this scene.
  21161. * @see BABYLON.AbstractMesh
  21162. * @type {BABYLON.AbstractMesh[]}
  21163. */
  21164. this.meshes = new Array();
  21165. /**
  21166. * All of the animation groups added to this scene.
  21167. * @see BABYLON.AnimationGroup
  21168. * @type {BABYLON.AnimationGroup[]}
  21169. */
  21170. this.animationGroups = new Array();
  21171. // Geometries
  21172. this._geometries = new Array();
  21173. this.materials = new Array();
  21174. this.multiMaterials = new Array();
  21175. // Textures
  21176. this._texturesEnabled = true;
  21177. this.textures = new Array();
  21178. // Particles
  21179. this.particlesEnabled = true;
  21180. this.particleSystems = new Array();
  21181. // Sprites
  21182. this.spritesEnabled = true;
  21183. this.spriteManagers = new Array();
  21184. /**
  21185. * The list of layers (background and foreground) of the scene.
  21186. */
  21187. this.layers = new Array();
  21188. /**
  21189. * The list of effect layers (highlights/glow) contained in the scene.
  21190. */
  21191. this.effectLayers = new Array();
  21192. // Skeletons
  21193. this._skeletonsEnabled = true;
  21194. this.skeletons = new Array();
  21195. // Morph targets
  21196. this.morphTargetManagers = new Array();
  21197. // Lens flares
  21198. this.lensFlaresEnabled = true;
  21199. this.lensFlareSystems = new Array();
  21200. // Collisions
  21201. this.collisionsEnabled = true;
  21202. /** Defines the gravity applied to this scene */
  21203. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21204. // Postprocesses
  21205. this.postProcesses = new Array();
  21206. this.postProcessesEnabled = true;
  21207. // Customs render targets
  21208. this.renderTargetsEnabled = true;
  21209. this.dumpNextRenderTargets = false;
  21210. this.customRenderTargets = new Array();
  21211. // Imported meshes
  21212. this.importedMeshesFiles = new Array();
  21213. // Probes
  21214. this.probesEnabled = true;
  21215. this.reflectionProbes = new Array();
  21216. this._actionManagers = new Array();
  21217. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21218. // Procedural textures
  21219. this.proceduralTexturesEnabled = true;
  21220. this._proceduralTextures = new Array();
  21221. this.soundTracks = new Array();
  21222. this._audioEnabled = true;
  21223. this._headphone = false;
  21224. // Performance counters
  21225. this._totalVertices = new BABYLON.PerfCounter();
  21226. this._activeIndices = new BABYLON.PerfCounter();
  21227. this._activeParticles = new BABYLON.PerfCounter();
  21228. this._activeBones = new BABYLON.PerfCounter();
  21229. this._animationTime = 0;
  21230. this.animationTimeScale = 1;
  21231. this._renderId = 0;
  21232. this._executeWhenReadyTimeoutId = -1;
  21233. this._intermediateRendering = false;
  21234. this._viewUpdateFlag = -1;
  21235. this._projectionUpdateFlag = -1;
  21236. this._alternateViewUpdateFlag = -1;
  21237. this._alternateProjectionUpdateFlag = -1;
  21238. this._toBeDisposed = new BABYLON.SmartArray(256);
  21239. this._activeRequests = new Array();
  21240. this._pendingData = new Array();
  21241. this._isDisposed = false;
  21242. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21243. this._activeMeshes = new BABYLON.SmartArray(256);
  21244. this._processedMaterials = new BABYLON.SmartArray(256);
  21245. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21246. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21247. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21248. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21249. this._activeAnimatables = new Array();
  21250. this._transformMatrix = BABYLON.Matrix.Zero();
  21251. this._useAlternateCameraConfiguration = false;
  21252. this._alternateRendering = false;
  21253. this.requireLightSorting = false;
  21254. this._activeMeshesFrozen = false;
  21255. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21256. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21257. this._engine.scenes.push(this);
  21258. this._uid = null;
  21259. this._renderingManager = new BABYLON.RenderingManager(this);
  21260. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21261. if (BABYLON.OutlineRenderer) {
  21262. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21263. }
  21264. if (BABYLON.Tools.IsWindowObjectExist()) {
  21265. this.attachControl();
  21266. }
  21267. //simplification queue
  21268. if (BABYLON.SimplificationQueue) {
  21269. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21270. }
  21271. //collision coordinator initialization. For now legacy per default.
  21272. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21273. // Uniform Buffer
  21274. this._createUbo();
  21275. // Default Image processing definition.
  21276. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21277. }
  21278. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21279. /** The fog is deactivated */
  21280. get: function () {
  21281. return Scene._FOGMODE_NONE;
  21282. },
  21283. enumerable: true,
  21284. configurable: true
  21285. });
  21286. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21287. /** The fog density is following an exponential function */
  21288. get: function () {
  21289. return Scene._FOGMODE_EXP;
  21290. },
  21291. enumerable: true,
  21292. configurable: true
  21293. });
  21294. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21295. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21296. get: function () {
  21297. return Scene._FOGMODE_EXP2;
  21298. },
  21299. enumerable: true,
  21300. configurable: true
  21301. });
  21302. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21303. /** The fog density is following a linear function. */
  21304. get: function () {
  21305. return Scene._FOGMODE_LINEAR;
  21306. },
  21307. enumerable: true,
  21308. configurable: true
  21309. });
  21310. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21311. /**
  21312. * Texture used in all pbr material as the reflection texture.
  21313. * As in the majority of the scene they are the same (exception for multi room and so on),
  21314. * this is easier to reference from here than from all the materials.
  21315. */
  21316. get: function () {
  21317. return this._environmentTexture;
  21318. },
  21319. /**
  21320. * Texture used in all pbr material as the reflection texture.
  21321. * As in the majority of the scene they are the same (exception for multi room and so on),
  21322. * this is easier to set here than in all the materials.
  21323. */
  21324. set: function (value) {
  21325. if (this._environmentTexture === value) {
  21326. return;
  21327. }
  21328. this._environmentTexture = value;
  21329. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21330. },
  21331. enumerable: true,
  21332. configurable: true
  21333. });
  21334. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21335. /**
  21336. * Default image processing configuration used either in the rendering
  21337. * Forward main pass or through the imageProcessingPostProcess if present.
  21338. * As in the majority of the scene they are the same (exception for multi camera),
  21339. * this is easier to reference from here than from all the materials and post process.
  21340. *
  21341. * No setter as we it is a shared configuration, you can set the values instead.
  21342. */
  21343. get: function () {
  21344. return this._imageProcessingConfiguration;
  21345. },
  21346. enumerable: true,
  21347. configurable: true
  21348. });
  21349. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21350. get: function () {
  21351. return this._forcePointsCloud;
  21352. },
  21353. set: function (value) {
  21354. if (this._forcePointsCloud === value) {
  21355. return;
  21356. }
  21357. this._forcePointsCloud = value;
  21358. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21359. },
  21360. enumerable: true,
  21361. configurable: true
  21362. });
  21363. Object.defineProperty(Scene.prototype, "onDispose", {
  21364. /** A function to be executed when this scene is disposed. */
  21365. set: function (callback) {
  21366. if (this._onDisposeObserver) {
  21367. this.onDisposeObservable.remove(this._onDisposeObserver);
  21368. }
  21369. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21370. },
  21371. enumerable: true,
  21372. configurable: true
  21373. });
  21374. Object.defineProperty(Scene.prototype, "beforeRender", {
  21375. /** A function to be executed before rendering this scene */
  21376. set: function (callback) {
  21377. if (this._onBeforeRenderObserver) {
  21378. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21379. }
  21380. if (callback) {
  21381. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21382. }
  21383. },
  21384. enumerable: true,
  21385. configurable: true
  21386. });
  21387. Object.defineProperty(Scene.prototype, "afterRender", {
  21388. /** A function to be executed after rendering this scene */
  21389. set: function (callback) {
  21390. if (this._onAfterRenderObserver) {
  21391. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21392. }
  21393. if (callback) {
  21394. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21395. }
  21396. },
  21397. enumerable: true,
  21398. configurable: true
  21399. });
  21400. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21401. set: function (callback) {
  21402. if (this._onBeforeCameraRenderObserver) {
  21403. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21404. }
  21405. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21406. },
  21407. enumerable: true,
  21408. configurable: true
  21409. });
  21410. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21411. set: function (callback) {
  21412. if (this._onAfterCameraRenderObserver) {
  21413. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21414. }
  21415. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21416. },
  21417. enumerable: true,
  21418. configurable: true
  21419. });
  21420. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21421. get: function () {
  21422. if (!this._gamepadManager) {
  21423. this._gamepadManager = new BABYLON.GamepadManager(this);
  21424. }
  21425. return this._gamepadManager;
  21426. },
  21427. enumerable: true,
  21428. configurable: true
  21429. });
  21430. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21431. get: function () {
  21432. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21433. },
  21434. enumerable: true,
  21435. configurable: true
  21436. });
  21437. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21438. get: function () {
  21439. return this._useRightHandedSystem;
  21440. },
  21441. set: function (value) {
  21442. if (this._useRightHandedSystem === value) {
  21443. return;
  21444. }
  21445. this._useRightHandedSystem = value;
  21446. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21447. },
  21448. enumerable: true,
  21449. configurable: true
  21450. });
  21451. Scene.prototype.setStepId = function (newStepId) {
  21452. this._currentStepId = newStepId;
  21453. };
  21454. ;
  21455. Scene.prototype.getStepId = function () {
  21456. return this._currentStepId;
  21457. };
  21458. ;
  21459. Scene.prototype.getInternalStep = function () {
  21460. return this._currentInternalStep;
  21461. };
  21462. ;
  21463. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21464. get: function () {
  21465. return this._fogEnabled;
  21466. },
  21467. /**
  21468. * is fog enabled on this scene.
  21469. */
  21470. set: function (value) {
  21471. if (this._fogEnabled === value) {
  21472. return;
  21473. }
  21474. this._fogEnabled = value;
  21475. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21476. },
  21477. enumerable: true,
  21478. configurable: true
  21479. });
  21480. Object.defineProperty(Scene.prototype, "fogMode", {
  21481. get: function () {
  21482. return this._fogMode;
  21483. },
  21484. set: function (value) {
  21485. if (this._fogMode === value) {
  21486. return;
  21487. }
  21488. this._fogMode = value;
  21489. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21490. },
  21491. enumerable: true,
  21492. configurable: true
  21493. });
  21494. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21495. get: function () {
  21496. return this._shadowsEnabled;
  21497. },
  21498. set: function (value) {
  21499. if (this._shadowsEnabled === value) {
  21500. return;
  21501. }
  21502. this._shadowsEnabled = value;
  21503. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21504. },
  21505. enumerable: true,
  21506. configurable: true
  21507. });
  21508. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21509. get: function () {
  21510. return this._lightsEnabled;
  21511. },
  21512. set: function (value) {
  21513. if (this._lightsEnabled === value) {
  21514. return;
  21515. }
  21516. this._lightsEnabled = value;
  21517. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21518. },
  21519. enumerable: true,
  21520. configurable: true
  21521. });
  21522. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21523. /** The default material used on meshes when no material is affected */
  21524. get: function () {
  21525. if (!this._defaultMaterial) {
  21526. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21527. }
  21528. return this._defaultMaterial;
  21529. },
  21530. /** The default material used on meshes when no material is affected */
  21531. set: function (value) {
  21532. this._defaultMaterial = value;
  21533. },
  21534. enumerable: true,
  21535. configurable: true
  21536. });
  21537. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21538. get: function () {
  21539. return this._texturesEnabled;
  21540. },
  21541. set: function (value) {
  21542. if (this._texturesEnabled === value) {
  21543. return;
  21544. }
  21545. this._texturesEnabled = value;
  21546. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21547. },
  21548. enumerable: true,
  21549. configurable: true
  21550. });
  21551. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21552. get: function () {
  21553. return this._skeletonsEnabled;
  21554. },
  21555. set: function (value) {
  21556. if (this._skeletonsEnabled === value) {
  21557. return;
  21558. }
  21559. this._skeletonsEnabled = value;
  21560. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21561. },
  21562. enumerable: true,
  21563. configurable: true
  21564. });
  21565. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21566. get: function () {
  21567. if (!this._postProcessRenderPipelineManager) {
  21568. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21569. }
  21570. return this._postProcessRenderPipelineManager;
  21571. },
  21572. enumerable: true,
  21573. configurable: true
  21574. });
  21575. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21576. get: function () {
  21577. if (!this._mainSoundTrack) {
  21578. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21579. }
  21580. return this._mainSoundTrack;
  21581. },
  21582. enumerable: true,
  21583. configurable: true
  21584. });
  21585. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21586. get: function () {
  21587. return this._alternateRendering;
  21588. },
  21589. enumerable: true,
  21590. configurable: true
  21591. });
  21592. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21593. get: function () {
  21594. return this._frustumPlanes;
  21595. },
  21596. enumerable: true,
  21597. configurable: true
  21598. });
  21599. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21600. /**
  21601. * Gets the current geometry buffer associated to the scene.
  21602. */
  21603. get: function () {
  21604. return this._geometryBufferRenderer;
  21605. },
  21606. /**
  21607. * Sets the current geometry buffer for the scene.
  21608. */
  21609. set: function (geometryBufferRenderer) {
  21610. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21611. this._geometryBufferRenderer = geometryBufferRenderer;
  21612. }
  21613. },
  21614. enumerable: true,
  21615. configurable: true
  21616. });
  21617. Object.defineProperty(Scene.prototype, "debugLayer", {
  21618. // Properties
  21619. get: function () {
  21620. if (!this._debugLayer) {
  21621. this._debugLayer = new BABYLON.DebugLayer(this);
  21622. }
  21623. return this._debugLayer;
  21624. },
  21625. enumerable: true,
  21626. configurable: true
  21627. });
  21628. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21629. get: function () {
  21630. return this._workerCollisions;
  21631. },
  21632. set: function (enabled) {
  21633. if (!BABYLON.CollisionCoordinatorLegacy) {
  21634. return;
  21635. }
  21636. enabled = (enabled && !!Worker);
  21637. this._workerCollisions = enabled;
  21638. if (this.collisionCoordinator) {
  21639. this.collisionCoordinator.destroy();
  21640. }
  21641. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21642. this.collisionCoordinator.init(this);
  21643. },
  21644. enumerable: true,
  21645. configurable: true
  21646. });
  21647. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21648. get: function () {
  21649. return this._selectionOctree;
  21650. },
  21651. enumerable: true,
  21652. configurable: true
  21653. });
  21654. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21655. /**
  21656. * The mesh that is currently under the pointer.
  21657. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21658. */
  21659. get: function () {
  21660. return this._pointerOverMesh;
  21661. },
  21662. enumerable: true,
  21663. configurable: true
  21664. });
  21665. Object.defineProperty(Scene.prototype, "pointerX", {
  21666. /**
  21667. * Current on-screen X position of the pointer
  21668. * @return {number} X position of the pointer
  21669. */
  21670. get: function () {
  21671. return this._pointerX;
  21672. },
  21673. enumerable: true,
  21674. configurable: true
  21675. });
  21676. Object.defineProperty(Scene.prototype, "pointerY", {
  21677. /**
  21678. * Current on-screen Y position of the pointer
  21679. * @return {number} Y position of the pointer
  21680. */
  21681. get: function () {
  21682. return this._pointerY;
  21683. },
  21684. enumerable: true,
  21685. configurable: true
  21686. });
  21687. Scene.prototype.getCachedMaterial = function () {
  21688. return this._cachedMaterial;
  21689. };
  21690. Scene.prototype.getCachedEffect = function () {
  21691. return this._cachedEffect;
  21692. };
  21693. Scene.prototype.getCachedVisibility = function () {
  21694. return this._cachedVisibility;
  21695. };
  21696. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21697. if (visibility === void 0) { visibility = 1; }
  21698. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21699. };
  21700. Scene.prototype.getBoundingBoxRenderer = function () {
  21701. if (!this._boundingBoxRenderer) {
  21702. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21703. }
  21704. return this._boundingBoxRenderer;
  21705. };
  21706. Scene.prototype.getOutlineRenderer = function () {
  21707. return this._outlineRenderer;
  21708. };
  21709. Scene.prototype.getEngine = function () {
  21710. return this._engine;
  21711. };
  21712. Scene.prototype.getTotalVertices = function () {
  21713. return this._totalVertices.current;
  21714. };
  21715. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21716. get: function () {
  21717. return this._totalVertices;
  21718. },
  21719. enumerable: true,
  21720. configurable: true
  21721. });
  21722. Scene.prototype.getActiveIndices = function () {
  21723. return this._activeIndices.current;
  21724. };
  21725. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21726. get: function () {
  21727. return this._activeIndices;
  21728. },
  21729. enumerable: true,
  21730. configurable: true
  21731. });
  21732. Scene.prototype.getActiveParticles = function () {
  21733. return this._activeParticles.current;
  21734. };
  21735. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21736. get: function () {
  21737. return this._activeParticles;
  21738. },
  21739. enumerable: true,
  21740. configurable: true
  21741. });
  21742. Scene.prototype.getActiveBones = function () {
  21743. return this._activeBones.current;
  21744. };
  21745. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  21746. get: function () {
  21747. return this._activeBones;
  21748. },
  21749. enumerable: true,
  21750. configurable: true
  21751. });
  21752. // Stats
  21753. Scene.prototype.getInterFramePerfCounter = function () {
  21754. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21755. return 0;
  21756. };
  21757. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  21758. get: function () {
  21759. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21760. return null;
  21761. },
  21762. enumerable: true,
  21763. configurable: true
  21764. });
  21765. Scene.prototype.getLastFrameDuration = function () {
  21766. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  21767. return 0;
  21768. };
  21769. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  21770. get: function () {
  21771. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21772. return null;
  21773. },
  21774. enumerable: true,
  21775. configurable: true
  21776. });
  21777. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  21778. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  21779. return 0;
  21780. };
  21781. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  21782. get: function () {
  21783. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21784. return null;
  21785. },
  21786. enumerable: true,
  21787. configurable: true
  21788. });
  21789. Scene.prototype.getActiveMeshes = function () {
  21790. return this._activeMeshes;
  21791. };
  21792. Scene.prototype.getRenderTargetsDuration = function () {
  21793. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  21794. return 0;
  21795. };
  21796. Scene.prototype.getRenderDuration = function () {
  21797. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  21798. return 0;
  21799. };
  21800. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  21801. get: function () {
  21802. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21803. return null;
  21804. },
  21805. enumerable: true,
  21806. configurable: true
  21807. });
  21808. Scene.prototype.getParticlesDuration = function () {
  21809. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  21810. return 0;
  21811. };
  21812. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  21813. get: function () {
  21814. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21815. return null;
  21816. },
  21817. enumerable: true,
  21818. configurable: true
  21819. });
  21820. Scene.prototype.getSpritesDuration = function () {
  21821. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  21822. return 0;
  21823. };
  21824. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  21825. get: function () {
  21826. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  21827. return null;
  21828. },
  21829. enumerable: true,
  21830. configurable: true
  21831. });
  21832. Scene.prototype.getAnimationRatio = function () {
  21833. return this._animationRatio;
  21834. };
  21835. Scene.prototype.getRenderId = function () {
  21836. return this._renderId;
  21837. };
  21838. Scene.prototype.incrementRenderId = function () {
  21839. this._renderId++;
  21840. };
  21841. Scene.prototype._updatePointerPosition = function (evt) {
  21842. var canvasRect = this._engine.getRenderingCanvasClientRect();
  21843. if (!canvasRect) {
  21844. return;
  21845. }
  21846. this._pointerX = evt.clientX - canvasRect.left;
  21847. this._pointerY = evt.clientY - canvasRect.top;
  21848. this._unTranslatedPointerX = this._pointerX;
  21849. this._unTranslatedPointerY = this._pointerY;
  21850. };
  21851. Scene.prototype._createUbo = function () {
  21852. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21853. this._sceneUbo.addUniform("viewProjection", 16);
  21854. this._sceneUbo.addUniform("view", 16);
  21855. };
  21856. Scene.prototype._createAlternateUbo = function () {
  21857. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21858. this._alternateSceneUbo.addUniform("viewProjection", 16);
  21859. this._alternateSceneUbo.addUniform("view", 16);
  21860. };
  21861. // Pointers handling
  21862. /**
  21863. * Use this method to simulate a pointer move on a mesh
  21864. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21865. */
  21866. Scene.prototype.simulatePointerMove = function (pickResult) {
  21867. var evt = new PointerEvent("pointermove");
  21868. return this._processPointerMove(pickResult, evt);
  21869. };
  21870. Scene.prototype._processPointerMove = function (pickResult, evt) {
  21871. var canvas = this._engine.getRenderingCanvas();
  21872. if (!canvas) {
  21873. return this;
  21874. }
  21875. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21876. this.setPointerOverSprite(null);
  21877. this.setPointerOverMesh(pickResult.pickedMesh);
  21878. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  21879. if (this._pointerOverMesh.actionManager.hoverCursor) {
  21880. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  21881. }
  21882. else {
  21883. canvas.style.cursor = this.hoverCursor;
  21884. }
  21885. }
  21886. else {
  21887. canvas.style.cursor = this.defaultCursor;
  21888. }
  21889. }
  21890. else {
  21891. this.setPointerOverMesh(null);
  21892. // Sprites
  21893. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  21894. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21895. this.setPointerOverSprite(pickResult.pickedSprite);
  21896. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  21897. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  21898. }
  21899. else {
  21900. canvas.style.cursor = this.hoverCursor;
  21901. }
  21902. }
  21903. else {
  21904. this.setPointerOverSprite(null);
  21905. // Restore pointer
  21906. canvas.style.cursor = this.defaultCursor;
  21907. }
  21908. }
  21909. if (pickResult) {
  21910. if (this.onPointerMove) {
  21911. this.onPointerMove(evt, pickResult);
  21912. }
  21913. if (this.onPointerObservable.hasObservers()) {
  21914. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21915. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21916. this.onPointerObservable.notifyObservers(pi, type);
  21917. }
  21918. }
  21919. return this;
  21920. };
  21921. /**
  21922. * Use this method to simulate a pointer down on a mesh
  21923. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21924. */
  21925. Scene.prototype.simulatePointerDown = function (pickResult) {
  21926. var evt = new PointerEvent("pointerdown");
  21927. return this._processPointerDown(pickResult, evt);
  21928. };
  21929. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21930. var _this = this;
  21931. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21932. this._pickedDownMesh = pickResult.pickedMesh;
  21933. var actionManager = pickResult.pickedMesh.actionManager;
  21934. if (actionManager) {
  21935. if (actionManager.hasPickTriggers) {
  21936. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21937. switch (evt.button) {
  21938. case 0:
  21939. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21940. break;
  21941. case 1:
  21942. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21943. break;
  21944. case 2:
  21945. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21946. break;
  21947. }
  21948. }
  21949. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21950. window.setTimeout(function () {
  21951. 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);
  21952. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21953. if (_this._totalPointersPressed !== 0 &&
  21954. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21955. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21956. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21957. _this._startingPointerTime = 0;
  21958. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21959. }
  21960. }
  21961. }, Scene.LongPressDelay);
  21962. }
  21963. }
  21964. }
  21965. if (pickResult) {
  21966. if (this.onPointerDown) {
  21967. this.onPointerDown(evt, pickResult);
  21968. }
  21969. if (this.onPointerObservable.hasObservers()) {
  21970. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21971. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21972. this.onPointerObservable.notifyObservers(pi, type);
  21973. }
  21974. }
  21975. return this;
  21976. };
  21977. /**
  21978. * Use this method to simulate a pointer up on a mesh
  21979. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21980. */
  21981. Scene.prototype.simulatePointerUp = function (pickResult) {
  21982. var evt = new PointerEvent("pointerup");
  21983. var clickInfo = new ClickInfo();
  21984. clickInfo.singleClick = true;
  21985. clickInfo.ignore = true;
  21986. return this._processPointerUp(pickResult, evt, clickInfo);
  21987. };
  21988. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21989. if (pickResult && pickResult && pickResult.pickedMesh) {
  21990. this._pickedUpMesh = pickResult.pickedMesh;
  21991. if (this._pickedDownMesh === this._pickedUpMesh) {
  21992. if (this.onPointerPick) {
  21993. this.onPointerPick(evt, pickResult);
  21994. }
  21995. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21996. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21997. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21998. this.onPointerObservable.notifyObservers(pi, type);
  21999. }
  22000. }
  22001. if (pickResult.pickedMesh.actionManager) {
  22002. if (clickInfo.ignore) {
  22003. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22004. }
  22005. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22006. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22007. }
  22008. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22009. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22010. }
  22011. }
  22012. }
  22013. if (this._pickedDownMesh &&
  22014. this._pickedDownMesh.actionManager &&
  22015. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22016. this._pickedDownMesh !== this._pickedUpMesh) {
  22017. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22018. }
  22019. if (this.onPointerUp) {
  22020. this.onPointerUp(evt, pickResult);
  22021. }
  22022. if (this.onPointerObservable.hasObservers()) {
  22023. if (!clickInfo.ignore) {
  22024. if (!clickInfo.hasSwiped) {
  22025. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22026. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22027. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22028. this.onPointerObservable.notifyObservers(pi, type);
  22029. }
  22030. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22031. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22032. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22033. this.onPointerObservable.notifyObservers(pi, type);
  22034. }
  22035. }
  22036. }
  22037. else {
  22038. var type = BABYLON.PointerEventTypes.POINTERUP;
  22039. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22040. this.onPointerObservable.notifyObservers(pi, type);
  22041. }
  22042. }
  22043. return this;
  22044. };
  22045. /**
  22046. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22047. * @param attachUp defines if you want to attach events to pointerup
  22048. * @param attachDown defines if you want to attach events to pointerdown
  22049. * @param attachMove defines if you want to attach events to pointermove
  22050. */
  22051. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22052. var _this = this;
  22053. if (attachUp === void 0) { attachUp = true; }
  22054. if (attachDown === void 0) { attachDown = true; }
  22055. if (attachMove === void 0) { attachMove = true; }
  22056. this._initActionManager = function (act, clickInfo) {
  22057. if (!_this._meshPickProceed) {
  22058. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22059. _this._currentPickResult = pickResult;
  22060. if (pickResult) {
  22061. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22062. }
  22063. _this._meshPickProceed = true;
  22064. }
  22065. return act;
  22066. };
  22067. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22068. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22069. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22070. btn !== _this._previousButtonPressed) {
  22071. _this._doubleClickOccured = false;
  22072. clickInfo.singleClick = true;
  22073. clickInfo.ignore = false;
  22074. cb(clickInfo, _this._currentPickResult);
  22075. }
  22076. };
  22077. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22078. var clickInfo = new ClickInfo();
  22079. _this._currentPickResult = null;
  22080. var act = null;
  22081. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22082. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22083. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22084. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22085. act = _this._initActionManager(act, clickInfo);
  22086. if (act)
  22087. checkPicking = act.hasPickTriggers;
  22088. }
  22089. if (checkPicking) {
  22090. var btn = evt.button;
  22091. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22092. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22093. if (!clickInfo.hasSwiped) {
  22094. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22095. if (!checkSingleClickImmediately) {
  22096. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22097. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22098. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22099. act = _this._initActionManager(act, clickInfo);
  22100. if (act)
  22101. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22102. }
  22103. }
  22104. if (checkSingleClickImmediately) {
  22105. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22106. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22107. btn !== _this._previousButtonPressed) {
  22108. clickInfo.singleClick = true;
  22109. cb(clickInfo, _this._currentPickResult);
  22110. }
  22111. }
  22112. else {
  22113. // wait that no double click has been raised during the double click delay
  22114. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22115. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22116. }
  22117. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22118. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22119. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22120. act = _this._initActionManager(act, clickInfo);
  22121. if (act)
  22122. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22123. }
  22124. if (checkDoubleClick) {
  22125. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22126. if (btn === _this._previousButtonPressed &&
  22127. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22128. !_this._doubleClickOccured) {
  22129. // pointer has not moved for 2 clicks, it's a double click
  22130. if (!clickInfo.hasSwiped &&
  22131. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22132. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22133. _this._previousStartingPointerTime = 0;
  22134. _this._doubleClickOccured = true;
  22135. clickInfo.doubleClick = true;
  22136. clickInfo.ignore = false;
  22137. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22138. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22139. }
  22140. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22141. cb(clickInfo, _this._currentPickResult);
  22142. }
  22143. else {
  22144. _this._doubleClickOccured = false;
  22145. _this._previousStartingPointerTime = _this._startingPointerTime;
  22146. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22147. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22148. _this._previousButtonPressed = btn;
  22149. if (Scene.ExclusiveDoubleClickMode) {
  22150. if (_this._previousDelayedSimpleClickTimeout) {
  22151. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22152. }
  22153. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22154. cb(clickInfo, _this._previousPickResult);
  22155. }
  22156. else {
  22157. cb(clickInfo, _this._currentPickResult);
  22158. }
  22159. }
  22160. }
  22161. else {
  22162. _this._doubleClickOccured = false;
  22163. _this._previousStartingPointerTime = _this._startingPointerTime;
  22164. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22165. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22166. _this._previousButtonPressed = btn;
  22167. }
  22168. }
  22169. }
  22170. }
  22171. clickInfo.ignore = true;
  22172. cb(clickInfo, _this._currentPickResult);
  22173. };
  22174. this._spritePredicate = function (sprite) {
  22175. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22176. };
  22177. this._onPointerMove = function (evt) {
  22178. _this._updatePointerPosition(evt);
  22179. // PreObservable support
  22180. if (_this.onPrePointerObservable.hasObservers()) {
  22181. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22182. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22183. _this.onPrePointerObservable.notifyObservers(pi, type);
  22184. if (pi.skipOnPointerObservable) {
  22185. return;
  22186. }
  22187. }
  22188. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22189. return;
  22190. }
  22191. if (!_this.pointerMovePredicate) {
  22192. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22193. }
  22194. // Meshes
  22195. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22196. _this._processPointerMove(pickResult, evt);
  22197. };
  22198. this._onPointerDown = function (evt) {
  22199. _this._totalPointersPressed++;
  22200. _this._pickedDownMesh = null;
  22201. _this._meshPickProceed = false;
  22202. _this._updatePointerPosition(evt);
  22203. if (_this.preventDefaultOnPointerDown && canvas) {
  22204. evt.preventDefault();
  22205. canvas.focus();
  22206. }
  22207. // PreObservable support
  22208. if (_this.onPrePointerObservable.hasObservers()) {
  22209. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22210. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22211. _this.onPrePointerObservable.notifyObservers(pi, type);
  22212. if (pi.skipOnPointerObservable) {
  22213. return;
  22214. }
  22215. }
  22216. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22217. return;
  22218. }
  22219. _this._startingPointerPosition.x = _this._pointerX;
  22220. _this._startingPointerPosition.y = _this._pointerY;
  22221. _this._startingPointerTime = new Date().getTime();
  22222. if (!_this.pointerDownPredicate) {
  22223. _this.pointerDownPredicate = function (mesh) {
  22224. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22225. };
  22226. }
  22227. // Meshes
  22228. _this._pickedDownMesh = null;
  22229. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22230. _this._processPointerDown(pickResult, evt);
  22231. // Sprites
  22232. _this._pickedDownSprite = null;
  22233. if (_this.spriteManagers.length > 0) {
  22234. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22235. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22236. if (pickResult.pickedSprite.actionManager) {
  22237. _this._pickedDownSprite = pickResult.pickedSprite;
  22238. switch (evt.button) {
  22239. case 0:
  22240. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22241. break;
  22242. case 1:
  22243. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22244. break;
  22245. case 2:
  22246. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22247. break;
  22248. }
  22249. if (pickResult.pickedSprite.actionManager) {
  22250. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22251. }
  22252. }
  22253. }
  22254. }
  22255. };
  22256. this._onPointerUp = function (evt) {
  22257. if (_this._totalPointersPressed === 0) {
  22258. return; // So we need to test it the pointer down was pressed before.
  22259. }
  22260. _this._totalPointersPressed--;
  22261. _this._pickedUpMesh = null;
  22262. _this._meshPickProceed = false;
  22263. _this._updatePointerPosition(evt);
  22264. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22265. // PreObservable support
  22266. if (_this.onPrePointerObservable.hasObservers()) {
  22267. if (!clickInfo.ignore) {
  22268. if (!clickInfo.hasSwiped) {
  22269. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22270. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22271. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22272. _this.onPrePointerObservable.notifyObservers(pi, type);
  22273. if (pi.skipOnPointerObservable) {
  22274. return;
  22275. }
  22276. }
  22277. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22278. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22279. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22280. _this.onPrePointerObservable.notifyObservers(pi, type);
  22281. if (pi.skipOnPointerObservable) {
  22282. return;
  22283. }
  22284. }
  22285. }
  22286. }
  22287. else {
  22288. var type = BABYLON.PointerEventTypes.POINTERUP;
  22289. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22290. _this.onPrePointerObservable.notifyObservers(pi, type);
  22291. if (pi.skipOnPointerObservable) {
  22292. return;
  22293. }
  22294. }
  22295. }
  22296. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22297. return;
  22298. }
  22299. if (!_this.pointerUpPredicate) {
  22300. _this.pointerUpPredicate = function (mesh) {
  22301. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22302. };
  22303. }
  22304. // Meshes
  22305. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22306. _this._initActionManager(null, clickInfo);
  22307. }
  22308. if (!pickResult) {
  22309. pickResult = _this._currentPickResult;
  22310. }
  22311. _this._processPointerUp(pickResult, evt, clickInfo);
  22312. // Sprites
  22313. if (_this.spriteManagers.length > 0) {
  22314. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22315. if (spritePickResult) {
  22316. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22317. if (spritePickResult.pickedSprite.actionManager) {
  22318. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22319. if (spritePickResult.pickedSprite.actionManager) {
  22320. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22321. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22322. }
  22323. }
  22324. }
  22325. }
  22326. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22327. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22328. }
  22329. }
  22330. }
  22331. _this._previousPickResult = _this._currentPickResult;
  22332. });
  22333. };
  22334. this._onKeyDown = function (evt) {
  22335. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22336. if (_this.onPreKeyboardObservable.hasObservers()) {
  22337. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22338. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22339. if (pi.skipOnPointerObservable) {
  22340. return;
  22341. }
  22342. }
  22343. if (_this.onKeyboardObservable.hasObservers()) {
  22344. var pi = new BABYLON.KeyboardInfo(type, evt);
  22345. _this.onKeyboardObservable.notifyObservers(pi, type);
  22346. }
  22347. if (_this.actionManager) {
  22348. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22349. }
  22350. };
  22351. this._onKeyUp = function (evt) {
  22352. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22353. if (_this.onPreKeyboardObservable.hasObservers()) {
  22354. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22355. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22356. if (pi.skipOnPointerObservable) {
  22357. return;
  22358. }
  22359. }
  22360. if (_this.onKeyboardObservable.hasObservers()) {
  22361. var pi = new BABYLON.KeyboardInfo(type, evt);
  22362. _this.onKeyboardObservable.notifyObservers(pi, type);
  22363. }
  22364. if (_this.actionManager) {
  22365. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22366. }
  22367. };
  22368. var engine = this.getEngine();
  22369. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22370. if (!canvas) {
  22371. return;
  22372. }
  22373. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22374. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22375. });
  22376. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22377. if (!canvas) {
  22378. return;
  22379. }
  22380. canvas.removeEventListener("keydown", _this._onKeyDown);
  22381. canvas.removeEventListener("keyup", _this._onKeyUp);
  22382. });
  22383. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22384. var canvas = this._engine.getRenderingCanvas();
  22385. if (!canvas) {
  22386. return;
  22387. }
  22388. if (attachMove) {
  22389. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22390. // Wheel
  22391. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22392. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22393. }
  22394. if (attachDown) {
  22395. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22396. }
  22397. if (attachUp) {
  22398. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22399. }
  22400. canvas.tabIndex = 1;
  22401. };
  22402. Scene.prototype.detachControl = function () {
  22403. var engine = this.getEngine();
  22404. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22405. var canvas = engine.getRenderingCanvas();
  22406. if (!canvas) {
  22407. return;
  22408. }
  22409. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22410. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22411. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22412. if (this._onCanvasBlurObserver) {
  22413. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22414. }
  22415. if (this._onCanvasFocusObserver) {
  22416. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22417. }
  22418. // Wheel
  22419. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22420. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22421. // Keyboard
  22422. canvas.removeEventListener("keydown", this._onKeyDown);
  22423. canvas.removeEventListener("keyup", this._onKeyUp);
  22424. // Observables
  22425. this.onKeyboardObservable.clear();
  22426. this.onPreKeyboardObservable.clear();
  22427. this.onPointerObservable.clear();
  22428. this.onPrePointerObservable.clear();
  22429. };
  22430. /**
  22431. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22432. * Delay loaded resources are not taking in account
  22433. * @return true if all required resources are ready
  22434. */
  22435. Scene.prototype.isReady = function () {
  22436. if (this._isDisposed) {
  22437. return false;
  22438. }
  22439. if (this._pendingData.length > 0) {
  22440. return false;
  22441. }
  22442. var index;
  22443. var engine = this.getEngine();
  22444. // Geometries
  22445. for (index = 0; index < this._geometries.length; index++) {
  22446. var geometry = this._geometries[index];
  22447. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22448. return false;
  22449. }
  22450. }
  22451. // Meshes
  22452. for (index = 0; index < this.meshes.length; index++) {
  22453. var mesh = this.meshes[index];
  22454. if (!mesh.isEnabled()) {
  22455. continue;
  22456. }
  22457. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22458. continue;
  22459. }
  22460. if (!mesh.isReady(true)) {
  22461. return false;
  22462. }
  22463. // Effect layers
  22464. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22465. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22466. var layer = _a[_i];
  22467. if (!layer.hasMesh(mesh)) {
  22468. continue;
  22469. }
  22470. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22471. var subMesh = _c[_b];
  22472. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22473. return false;
  22474. }
  22475. }
  22476. }
  22477. }
  22478. return true;
  22479. };
  22480. Scene.prototype.resetCachedMaterial = function () {
  22481. this._cachedMaterial = null;
  22482. this._cachedEffect = null;
  22483. this._cachedVisibility = null;
  22484. };
  22485. Scene.prototype.registerBeforeRender = function (func) {
  22486. this.onBeforeRenderObservable.add(func);
  22487. };
  22488. Scene.prototype.unregisterBeforeRender = function (func) {
  22489. this.onBeforeRenderObservable.removeCallback(func);
  22490. };
  22491. Scene.prototype.registerAfterRender = function (func) {
  22492. this.onAfterRenderObservable.add(func);
  22493. };
  22494. Scene.prototype.unregisterAfterRender = function (func) {
  22495. this.onAfterRenderObservable.removeCallback(func);
  22496. };
  22497. Scene.prototype._executeOnceBeforeRender = function (func) {
  22498. var _this = this;
  22499. var execFunc = function () {
  22500. func();
  22501. setTimeout(function () {
  22502. _this.unregisterBeforeRender(execFunc);
  22503. });
  22504. };
  22505. this.registerBeforeRender(execFunc);
  22506. };
  22507. /**
  22508. * The provided function will run before render once and will be disposed afterwards.
  22509. * A timeout delay can be provided so that the function will be executed in N ms.
  22510. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22511. * @param func The function to be executed.
  22512. * @param timeout optional delay in ms
  22513. */
  22514. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22515. var _this = this;
  22516. if (timeout !== undefined) {
  22517. setTimeout(function () {
  22518. _this._executeOnceBeforeRender(func);
  22519. }, timeout);
  22520. }
  22521. else {
  22522. this._executeOnceBeforeRender(func);
  22523. }
  22524. };
  22525. Scene.prototype._addPendingData = function (data) {
  22526. this._pendingData.push(data);
  22527. };
  22528. Scene.prototype._removePendingData = function (data) {
  22529. var wasLoading = this.isLoading;
  22530. var index = this._pendingData.indexOf(data);
  22531. if (index !== -1) {
  22532. this._pendingData.splice(index, 1);
  22533. }
  22534. if (wasLoading && !this.isLoading) {
  22535. this.onDataLoadedObservable.notifyObservers(this);
  22536. }
  22537. };
  22538. Scene.prototype.getWaitingItemsCount = function () {
  22539. return this._pendingData.length;
  22540. };
  22541. Object.defineProperty(Scene.prototype, "isLoading", {
  22542. get: function () {
  22543. return this._pendingData.length > 0;
  22544. },
  22545. enumerable: true,
  22546. configurable: true
  22547. });
  22548. /**
  22549. * Registers a function to be executed when the scene is ready.
  22550. * @param {Function} func - the function to be executed.
  22551. */
  22552. Scene.prototype.executeWhenReady = function (func) {
  22553. var _this = this;
  22554. this.onReadyObservable.add(func);
  22555. if (this._executeWhenReadyTimeoutId !== -1) {
  22556. return;
  22557. }
  22558. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22559. _this._checkIsReady();
  22560. }, 150);
  22561. };
  22562. /**
  22563. * Returns a promise that resolves when the scene is ready.
  22564. * @returns A promise that resolves when the scene is ready.
  22565. */
  22566. Scene.prototype.whenReadyAsync = function () {
  22567. var _this = this;
  22568. return new Promise(function (resolve) {
  22569. _this.executeWhenReady(function () {
  22570. resolve();
  22571. });
  22572. });
  22573. };
  22574. Scene.prototype._checkIsReady = function () {
  22575. var _this = this;
  22576. if (this.isReady()) {
  22577. this.onReadyObservable.notifyObservers(this);
  22578. this.onReadyObservable.clear();
  22579. this._executeWhenReadyTimeoutId = -1;
  22580. return;
  22581. }
  22582. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22583. _this._checkIsReady();
  22584. }, 150);
  22585. };
  22586. // Animations
  22587. /**
  22588. * Will start the animation sequence of a given target
  22589. * @param target - the target
  22590. * @param {number} from - from which frame should animation start
  22591. * @param {number} to - till which frame should animation run.
  22592. * @param {boolean} [loop] - should the animation loop
  22593. * @param {number} [speedRatio] - the speed in which to run the animation
  22594. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22595. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22596. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22597. * See BABYLON.Animatable
  22598. */
  22599. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22600. if (speedRatio === void 0) { speedRatio = 1.0; }
  22601. if (from > to && speedRatio > 0) {
  22602. speedRatio *= -1;
  22603. }
  22604. this.stopAnimation(target);
  22605. if (!animatable) {
  22606. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22607. }
  22608. // Local animations
  22609. if (target.animations) {
  22610. animatable.appendAnimations(target, target.animations);
  22611. }
  22612. // Children animations
  22613. if (target.getAnimatables) {
  22614. var animatables = target.getAnimatables();
  22615. for (var index = 0; index < animatables.length; index++) {
  22616. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22617. }
  22618. }
  22619. animatable.reset();
  22620. return animatable;
  22621. };
  22622. /**
  22623. * Begin a new animation on a given node
  22624. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22625. * @param {BABYLON.Animation[]} defines the list of animations to start
  22626. * @param {number} from defines the initial value
  22627. * @param {number} to defines the final value
  22628. * @param {boolean} loop defines if you want animation to loop (off by default)
  22629. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22630. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22631. * @returns the list of created animatables
  22632. */
  22633. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22634. if (speedRatio === undefined) {
  22635. speedRatio = 1.0;
  22636. }
  22637. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22638. return animatable;
  22639. };
  22640. /**
  22641. * Begin a new animation on a given node and its hierarchy
  22642. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22643. * @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.
  22644. * @param {BABYLON.Animation[]} defines the list of animations to start
  22645. * @param {number} from defines the initial value
  22646. * @param {number} to defines the final value
  22647. * @param {boolean} loop defines if you want animation to loop (off by default)
  22648. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22649. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22650. * @returns the list of animatables created for all nodes
  22651. */
  22652. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22653. var children = target.getDescendants(directDescendantsOnly);
  22654. var result = [];
  22655. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22656. var child = children_1[_i];
  22657. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22658. }
  22659. return result;
  22660. };
  22661. Scene.prototype.getAnimatableByTarget = function (target) {
  22662. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22663. if (this._activeAnimatables[index].target === target) {
  22664. return this._activeAnimatables[index];
  22665. }
  22666. }
  22667. return null;
  22668. };
  22669. Object.defineProperty(Scene.prototype, "animatables", {
  22670. get: function () {
  22671. return this._activeAnimatables;
  22672. },
  22673. enumerable: true,
  22674. configurable: true
  22675. });
  22676. /**
  22677. * Will stop the animation of the given target
  22678. * @param target - the target
  22679. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22680. * @see beginAnimation
  22681. */
  22682. Scene.prototype.stopAnimation = function (target, animationName) {
  22683. var animatable = this.getAnimatableByTarget(target);
  22684. if (animatable) {
  22685. animatable.stop(animationName);
  22686. }
  22687. };
  22688. /**
  22689. * Stops and removes all animations that have been applied to the scene
  22690. */
  22691. Scene.prototype.stopAllAnimations = function () {
  22692. if (this._activeAnimatables) {
  22693. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22694. this._activeAnimatables[i].stop();
  22695. }
  22696. this._activeAnimatables = [];
  22697. }
  22698. };
  22699. Scene.prototype._animate = function () {
  22700. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22701. return;
  22702. }
  22703. // Getting time
  22704. var now = BABYLON.Tools.Now;
  22705. if (!this._animationTimeLast) {
  22706. if (this._pendingData.length > 0) {
  22707. return;
  22708. }
  22709. this._animationTimeLast = now;
  22710. }
  22711. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22712. this._animationTime += deltaTime;
  22713. this._animationTimeLast = now;
  22714. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22715. this._activeAnimatables[index]._animate(this._animationTime);
  22716. }
  22717. };
  22718. // Matrix
  22719. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22720. this._useAlternateCameraConfiguration = active;
  22721. };
  22722. Scene.prototype.getViewMatrix = function () {
  22723. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22724. };
  22725. Scene.prototype.getProjectionMatrix = function () {
  22726. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22727. };
  22728. Scene.prototype.getTransformMatrix = function () {
  22729. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22730. };
  22731. Scene.prototype.setTransformMatrix = function (view, projection) {
  22732. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22733. return;
  22734. }
  22735. this._viewUpdateFlag = view.updateFlag;
  22736. this._projectionUpdateFlag = projection.updateFlag;
  22737. this._viewMatrix = view;
  22738. this._projectionMatrix = projection;
  22739. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22740. // Update frustum
  22741. if (!this._frustumPlanes) {
  22742. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22743. }
  22744. else {
  22745. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22746. }
  22747. if (this.activeCamera && this.activeCamera._alternateCamera) {
  22748. var otherCamera = this.activeCamera._alternateCamera;
  22749. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  22750. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  22751. }
  22752. if (this._sceneUbo.useUbo) {
  22753. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  22754. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  22755. this._sceneUbo.update();
  22756. }
  22757. };
  22758. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  22759. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  22760. return;
  22761. }
  22762. this._alternateViewUpdateFlag = view.updateFlag;
  22763. this._alternateProjectionUpdateFlag = projection.updateFlag;
  22764. this._alternateViewMatrix = view;
  22765. this._alternateProjectionMatrix = projection;
  22766. if (!this._alternateTransformMatrix) {
  22767. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  22768. }
  22769. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  22770. if (!this._alternateSceneUbo) {
  22771. this._createAlternateUbo();
  22772. }
  22773. if (this._alternateSceneUbo.useUbo) {
  22774. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  22775. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  22776. this._alternateSceneUbo.update();
  22777. }
  22778. };
  22779. Scene.prototype.getSceneUniformBuffer = function () {
  22780. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  22781. };
  22782. // Methods
  22783. Scene.prototype.getUniqueId = function () {
  22784. var result = Scene._uniqueIdCounter;
  22785. Scene._uniqueIdCounter++;
  22786. return result;
  22787. };
  22788. Scene.prototype.addMesh = function (newMesh) {
  22789. this.meshes.push(newMesh);
  22790. //notify the collision coordinator
  22791. if (this.collisionCoordinator) {
  22792. this.collisionCoordinator.onMeshAdded(newMesh);
  22793. }
  22794. newMesh._resyncLightSources();
  22795. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  22796. };
  22797. Scene.prototype.removeMesh = function (toRemove) {
  22798. var index = this.meshes.indexOf(toRemove);
  22799. if (index !== -1) {
  22800. // Remove from the scene if mesh found
  22801. this.meshes.splice(index, 1);
  22802. }
  22803. this.onMeshRemovedObservable.notifyObservers(toRemove);
  22804. return index;
  22805. };
  22806. Scene.prototype.addTransformNode = function (newTransformNode) {
  22807. this.transformNodes.push(newTransformNode);
  22808. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  22809. };
  22810. Scene.prototype.removeTransformNode = function (toRemove) {
  22811. var index = this.transformNodes.indexOf(toRemove);
  22812. if (index !== -1) {
  22813. // Remove from the scene if found
  22814. this.transformNodes.splice(index, 1);
  22815. }
  22816. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  22817. return index;
  22818. };
  22819. Scene.prototype.removeSkeleton = function (toRemove) {
  22820. var index = this.skeletons.indexOf(toRemove);
  22821. if (index !== -1) {
  22822. // Remove from the scene if found
  22823. this.skeletons.splice(index, 1);
  22824. }
  22825. return index;
  22826. };
  22827. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  22828. var index = this.morphTargetManagers.indexOf(toRemove);
  22829. if (index !== -1) {
  22830. // Remove from the scene if found
  22831. this.morphTargetManagers.splice(index, 1);
  22832. }
  22833. return index;
  22834. };
  22835. Scene.prototype.removeLight = function (toRemove) {
  22836. var index = this.lights.indexOf(toRemove);
  22837. if (index !== -1) {
  22838. // Remove from meshes
  22839. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22840. var mesh = _a[_i];
  22841. mesh._removeLightSource(toRemove);
  22842. }
  22843. // Remove from the scene if mesh found
  22844. this.lights.splice(index, 1);
  22845. this.sortLightsByPriority();
  22846. }
  22847. this.onLightRemovedObservable.notifyObservers(toRemove);
  22848. return index;
  22849. };
  22850. Scene.prototype.removeCamera = function (toRemove) {
  22851. var index = this.cameras.indexOf(toRemove);
  22852. if (index !== -1) {
  22853. // Remove from the scene if mesh found
  22854. this.cameras.splice(index, 1);
  22855. }
  22856. // Remove from activeCameras
  22857. var index2 = this.activeCameras.indexOf(toRemove);
  22858. if (index2 !== -1) {
  22859. // Remove from the scene if mesh found
  22860. this.activeCameras.splice(index2, 1);
  22861. }
  22862. // Reset the activeCamera
  22863. if (this.activeCamera === toRemove) {
  22864. if (this.cameras.length > 0) {
  22865. this.activeCamera = this.cameras[0];
  22866. }
  22867. else {
  22868. this.activeCamera = null;
  22869. }
  22870. }
  22871. this.onCameraRemovedObservable.notifyObservers(toRemove);
  22872. return index;
  22873. };
  22874. Scene.prototype.removeParticleSystem = function (toRemove) {
  22875. var index = this.particleSystems.indexOf(toRemove);
  22876. if (index !== -1) {
  22877. this.particleSystems.splice(index, 1);
  22878. }
  22879. return index;
  22880. };
  22881. ;
  22882. Scene.prototype.removeAnimation = function (toRemove) {
  22883. var index = this.animations.indexOf(toRemove);
  22884. if (index !== -1) {
  22885. this.animations.splice(index, 1);
  22886. }
  22887. return index;
  22888. };
  22889. ;
  22890. Scene.prototype.removeMultiMaterial = function (toRemove) {
  22891. var index = this.multiMaterials.indexOf(toRemove);
  22892. if (index !== -1) {
  22893. this.multiMaterials.splice(index, 1);
  22894. }
  22895. return index;
  22896. };
  22897. ;
  22898. Scene.prototype.removeMaterial = function (toRemove) {
  22899. var index = this.materials.indexOf(toRemove);
  22900. if (index !== -1) {
  22901. this.materials.splice(index, 1);
  22902. }
  22903. return index;
  22904. };
  22905. ;
  22906. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  22907. var index = this.lensFlareSystems.indexOf(toRemove);
  22908. if (index !== -1) {
  22909. this.lensFlareSystems.splice(index, 1);
  22910. }
  22911. return index;
  22912. };
  22913. ;
  22914. Scene.prototype.removeActionManager = function (toRemove) {
  22915. var index = this._actionManagers.indexOf(toRemove);
  22916. if (index !== -1) {
  22917. this._actionManagers.splice(index, 1);
  22918. }
  22919. return index;
  22920. };
  22921. ;
  22922. Scene.prototype.addLight = function (newLight) {
  22923. this.lights.push(newLight);
  22924. this.sortLightsByPriority();
  22925. // Add light to all meshes (To support if the light is removed and then readded)
  22926. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22927. var mesh = _a[_i];
  22928. if (mesh._lightSources.indexOf(newLight) === -1) {
  22929. mesh._lightSources.push(newLight);
  22930. mesh._resyncLightSources();
  22931. }
  22932. }
  22933. this.onNewLightAddedObservable.notifyObservers(newLight);
  22934. };
  22935. Scene.prototype.sortLightsByPriority = function () {
  22936. if (this.requireLightSorting) {
  22937. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22938. }
  22939. };
  22940. Scene.prototype.addCamera = function (newCamera) {
  22941. this.cameras.push(newCamera);
  22942. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22943. };
  22944. Scene.prototype.addSkeleton = function (newSkeleton) {
  22945. this.skeletons.push(newSkeleton);
  22946. };
  22947. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22948. this.particleSystems.push(newParticleSystem);
  22949. };
  22950. Scene.prototype.addAnimation = function (newAnimation) {
  22951. this.animations.push(newAnimation);
  22952. };
  22953. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22954. this.multiMaterials.push(newMultiMaterial);
  22955. };
  22956. Scene.prototype.addMaterial = function (newMaterial) {
  22957. this.materials.push(newMaterial);
  22958. };
  22959. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22960. this.morphTargetManagers.push(newMorphTargetManager);
  22961. };
  22962. Scene.prototype.addGeometry = function (newGeometrie) {
  22963. this._geometries.push(newGeometrie);
  22964. };
  22965. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22966. this.lensFlareSystems.push(newLensFlareSystem);
  22967. };
  22968. Scene.prototype.addActionManager = function (newActionManager) {
  22969. this._actionManagers.push(newActionManager);
  22970. };
  22971. /**
  22972. * Switch active camera
  22973. * @param {Camera} newCamera - new active camera
  22974. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22975. */
  22976. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22977. if (attachControl === void 0) { attachControl = true; }
  22978. var canvas = this._engine.getRenderingCanvas();
  22979. if (!canvas) {
  22980. return;
  22981. }
  22982. if (this.activeCamera) {
  22983. this.activeCamera.detachControl(canvas);
  22984. }
  22985. this.activeCamera = newCamera;
  22986. if (attachControl) {
  22987. newCamera.attachControl(canvas);
  22988. }
  22989. };
  22990. /**
  22991. * sets the active camera of the scene using its ID
  22992. * @param {string} id - the camera's ID
  22993. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22994. * @see activeCamera
  22995. */
  22996. Scene.prototype.setActiveCameraByID = function (id) {
  22997. var camera = this.getCameraByID(id);
  22998. if (camera) {
  22999. this.activeCamera = camera;
  23000. return camera;
  23001. }
  23002. return null;
  23003. };
  23004. /**
  23005. * sets the active camera of the scene using its name
  23006. * @param {string} name - the camera's name
  23007. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23008. * @see activeCamera
  23009. */
  23010. Scene.prototype.setActiveCameraByName = function (name) {
  23011. var camera = this.getCameraByName(name);
  23012. if (camera) {
  23013. this.activeCamera = camera;
  23014. return camera;
  23015. }
  23016. return null;
  23017. };
  23018. /**
  23019. * get an animation group using its name
  23020. * @param {string} the material's name
  23021. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23022. */
  23023. Scene.prototype.getAnimationGroupByName = function (name) {
  23024. for (var index = 0; index < this.animationGroups.length; index++) {
  23025. if (this.animationGroups[index].name === name) {
  23026. return this.animationGroups[index];
  23027. }
  23028. }
  23029. return null;
  23030. };
  23031. /**
  23032. * get a material using its id
  23033. * @param {string} the material's ID
  23034. * @return {BABYLON.Material|null} the material or null if none found.
  23035. */
  23036. Scene.prototype.getMaterialByID = function (id) {
  23037. for (var index = 0; index < this.materials.length; index++) {
  23038. if (this.materials[index].id === id) {
  23039. return this.materials[index];
  23040. }
  23041. }
  23042. return null;
  23043. };
  23044. /**
  23045. * get a material using its name
  23046. * @param {string} the material's name
  23047. * @return {BABYLON.Material|null} the material or null if none found.
  23048. */
  23049. Scene.prototype.getMaterialByName = function (name) {
  23050. for (var index = 0; index < this.materials.length; index++) {
  23051. if (this.materials[index].name === name) {
  23052. return this.materials[index];
  23053. }
  23054. }
  23055. return null;
  23056. };
  23057. Scene.prototype.getLensFlareSystemByName = function (name) {
  23058. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23059. if (this.lensFlareSystems[index].name === name) {
  23060. return this.lensFlareSystems[index];
  23061. }
  23062. }
  23063. return null;
  23064. };
  23065. Scene.prototype.getLensFlareSystemByID = function (id) {
  23066. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23067. if (this.lensFlareSystems[index].id === id) {
  23068. return this.lensFlareSystems[index];
  23069. }
  23070. }
  23071. return null;
  23072. };
  23073. Scene.prototype.getCameraByID = function (id) {
  23074. for (var index = 0; index < this.cameras.length; index++) {
  23075. if (this.cameras[index].id === id) {
  23076. return this.cameras[index];
  23077. }
  23078. }
  23079. return null;
  23080. };
  23081. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23082. for (var index = 0; index < this.cameras.length; index++) {
  23083. if (this.cameras[index].uniqueId === uniqueId) {
  23084. return this.cameras[index];
  23085. }
  23086. }
  23087. return null;
  23088. };
  23089. /**
  23090. * get a camera using its name
  23091. * @param {string} the camera's name
  23092. * @return {BABYLON.Camera|null} the camera or null if none found.
  23093. */
  23094. Scene.prototype.getCameraByName = function (name) {
  23095. for (var index = 0; index < this.cameras.length; index++) {
  23096. if (this.cameras[index].name === name) {
  23097. return this.cameras[index];
  23098. }
  23099. }
  23100. return null;
  23101. };
  23102. /**
  23103. * get a bone using its id
  23104. * @param {string} the bone's id
  23105. * @return {BABYLON.Bone|null} the bone or null if not found
  23106. */
  23107. Scene.prototype.getBoneByID = function (id) {
  23108. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23109. var skeleton = this.skeletons[skeletonIndex];
  23110. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23111. if (skeleton.bones[boneIndex].id === id) {
  23112. return skeleton.bones[boneIndex];
  23113. }
  23114. }
  23115. }
  23116. return null;
  23117. };
  23118. /**
  23119. * get a bone using its id
  23120. * @param {string} the bone's name
  23121. * @return {BABYLON.Bone|null} the bone or null if not found
  23122. */
  23123. Scene.prototype.getBoneByName = function (name) {
  23124. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23125. var skeleton = this.skeletons[skeletonIndex];
  23126. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23127. if (skeleton.bones[boneIndex].name === name) {
  23128. return skeleton.bones[boneIndex];
  23129. }
  23130. }
  23131. }
  23132. return null;
  23133. };
  23134. /**
  23135. * get a light node using its name
  23136. * @param {string} the light's name
  23137. * @return {BABYLON.Light|null} the light or null if none found.
  23138. */
  23139. Scene.prototype.getLightByName = function (name) {
  23140. for (var index = 0; index < this.lights.length; index++) {
  23141. if (this.lights[index].name === name) {
  23142. return this.lights[index];
  23143. }
  23144. }
  23145. return null;
  23146. };
  23147. /**
  23148. * get a light node using its ID
  23149. * @param {string} the light's id
  23150. * @return {BABYLON.Light|null} the light or null if none found.
  23151. */
  23152. Scene.prototype.getLightByID = function (id) {
  23153. for (var index = 0; index < this.lights.length; index++) {
  23154. if (this.lights[index].id === id) {
  23155. return this.lights[index];
  23156. }
  23157. }
  23158. return null;
  23159. };
  23160. /**
  23161. * get a light node using its scene-generated unique ID
  23162. * @param {number} the light's unique id
  23163. * @return {BABYLON.Light|null} the light or null if none found.
  23164. */
  23165. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23166. for (var index = 0; index < this.lights.length; index++) {
  23167. if (this.lights[index].uniqueId === uniqueId) {
  23168. return this.lights[index];
  23169. }
  23170. }
  23171. return null;
  23172. };
  23173. /**
  23174. * get a particle system by id
  23175. * @param id {number} the particle system id
  23176. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23177. */
  23178. Scene.prototype.getParticleSystemByID = function (id) {
  23179. for (var index = 0; index < this.particleSystems.length; index++) {
  23180. if (this.particleSystems[index].id === id) {
  23181. return this.particleSystems[index];
  23182. }
  23183. }
  23184. return null;
  23185. };
  23186. /**
  23187. * get a geometry using its ID
  23188. * @param {string} the geometry's id
  23189. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23190. */
  23191. Scene.prototype.getGeometryByID = function (id) {
  23192. for (var index = 0; index < this._geometries.length; index++) {
  23193. if (this._geometries[index].id === id) {
  23194. return this._geometries[index];
  23195. }
  23196. }
  23197. return null;
  23198. };
  23199. /**
  23200. * add a new geometry to this scene.
  23201. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23202. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23203. * @return {boolean} was the geometry added or not
  23204. */
  23205. Scene.prototype.pushGeometry = function (geometry, force) {
  23206. if (!force && this.getGeometryByID(geometry.id)) {
  23207. return false;
  23208. }
  23209. this._geometries.push(geometry);
  23210. //notify the collision coordinator
  23211. if (this.collisionCoordinator) {
  23212. this.collisionCoordinator.onGeometryAdded(geometry);
  23213. }
  23214. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23215. return true;
  23216. };
  23217. /**
  23218. * Removes an existing geometry
  23219. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23220. * @return {boolean} was the geometry removed or not
  23221. */
  23222. Scene.prototype.removeGeometry = function (geometry) {
  23223. var index = this._geometries.indexOf(geometry);
  23224. if (index > -1) {
  23225. this._geometries.splice(index, 1);
  23226. //notify the collision coordinator
  23227. if (this.collisionCoordinator) {
  23228. this.collisionCoordinator.onGeometryDeleted(geometry);
  23229. }
  23230. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23231. return true;
  23232. }
  23233. return false;
  23234. };
  23235. Scene.prototype.getGeometries = function () {
  23236. return this._geometries;
  23237. };
  23238. /**
  23239. * Get the first added mesh found of a given ID
  23240. * @param {string} id - the id to search for
  23241. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23242. */
  23243. Scene.prototype.getMeshByID = function (id) {
  23244. for (var index = 0; index < this.meshes.length; index++) {
  23245. if (this.meshes[index].id === id) {
  23246. return this.meshes[index];
  23247. }
  23248. }
  23249. return null;
  23250. };
  23251. Scene.prototype.getMeshesByID = function (id) {
  23252. return this.meshes.filter(function (m) {
  23253. return m.id === id;
  23254. });
  23255. };
  23256. /**
  23257. * Get the first added transform node found of a given ID
  23258. * @param {string} id - the id to search for
  23259. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23260. */
  23261. Scene.prototype.getTransformNodeByID = function (id) {
  23262. for (var index = 0; index < this.transformNodes.length; index++) {
  23263. if (this.transformNodes[index].id === id) {
  23264. return this.transformNodes[index];
  23265. }
  23266. }
  23267. return null;
  23268. };
  23269. Scene.prototype.getTransformNodesByID = function (id) {
  23270. return this.transformNodes.filter(function (m) {
  23271. return m.id === id;
  23272. });
  23273. };
  23274. /**
  23275. * Get a mesh with its auto-generated unique id
  23276. * @param {number} uniqueId - the unique id to search for
  23277. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23278. */
  23279. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23280. for (var index = 0; index < this.meshes.length; index++) {
  23281. if (this.meshes[index].uniqueId === uniqueId) {
  23282. return this.meshes[index];
  23283. }
  23284. }
  23285. return null;
  23286. };
  23287. /**
  23288. * Get a the last added mesh found of a given ID
  23289. * @param {string} id - the id to search for
  23290. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23291. */
  23292. Scene.prototype.getLastMeshByID = function (id) {
  23293. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23294. if (this.meshes[index].id === id) {
  23295. return this.meshes[index];
  23296. }
  23297. }
  23298. return null;
  23299. };
  23300. /**
  23301. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23302. * @param {string} id - the id to search for
  23303. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23304. */
  23305. Scene.prototype.getLastEntryByID = function (id) {
  23306. var index;
  23307. for (index = this.meshes.length - 1; index >= 0; index--) {
  23308. if (this.meshes[index].id === id) {
  23309. return this.meshes[index];
  23310. }
  23311. }
  23312. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23313. if (this.transformNodes[index].id === id) {
  23314. return this.transformNodes[index];
  23315. }
  23316. }
  23317. for (index = this.cameras.length - 1; index >= 0; index--) {
  23318. if (this.cameras[index].id === id) {
  23319. return this.cameras[index];
  23320. }
  23321. }
  23322. for (index = this.lights.length - 1; index >= 0; index--) {
  23323. if (this.lights[index].id === id) {
  23324. return this.lights[index];
  23325. }
  23326. }
  23327. return null;
  23328. };
  23329. Scene.prototype.getNodeByID = function (id) {
  23330. var mesh = this.getMeshByID(id);
  23331. if (mesh) {
  23332. return mesh;
  23333. }
  23334. var light = this.getLightByID(id);
  23335. if (light) {
  23336. return light;
  23337. }
  23338. var camera = this.getCameraByID(id);
  23339. if (camera) {
  23340. return camera;
  23341. }
  23342. var bone = this.getBoneByID(id);
  23343. return bone;
  23344. };
  23345. Scene.prototype.getNodeByName = function (name) {
  23346. var mesh = this.getMeshByName(name);
  23347. if (mesh) {
  23348. return mesh;
  23349. }
  23350. var light = this.getLightByName(name);
  23351. if (light) {
  23352. return light;
  23353. }
  23354. var camera = this.getCameraByName(name);
  23355. if (camera) {
  23356. return camera;
  23357. }
  23358. var bone = this.getBoneByName(name);
  23359. return bone;
  23360. };
  23361. Scene.prototype.getMeshByName = function (name) {
  23362. for (var index = 0; index < this.meshes.length; index++) {
  23363. if (this.meshes[index].name === name) {
  23364. return this.meshes[index];
  23365. }
  23366. }
  23367. return null;
  23368. };
  23369. Scene.prototype.getTransformNodeByName = function (name) {
  23370. for (var index = 0; index < this.transformNodes.length; index++) {
  23371. if (this.transformNodes[index].name === name) {
  23372. return this.transformNodes[index];
  23373. }
  23374. }
  23375. return null;
  23376. };
  23377. Scene.prototype.getSoundByName = function (name) {
  23378. var index;
  23379. if (BABYLON.AudioEngine) {
  23380. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23381. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23382. return this.mainSoundTrack.soundCollection[index];
  23383. }
  23384. }
  23385. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23386. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23387. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23388. return this.soundTracks[sdIndex].soundCollection[index];
  23389. }
  23390. }
  23391. }
  23392. }
  23393. return null;
  23394. };
  23395. Scene.prototype.getLastSkeletonByID = function (id) {
  23396. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23397. if (this.skeletons[index].id === id) {
  23398. return this.skeletons[index];
  23399. }
  23400. }
  23401. return null;
  23402. };
  23403. Scene.prototype.getSkeletonById = function (id) {
  23404. for (var index = 0; index < this.skeletons.length; index++) {
  23405. if (this.skeletons[index].id === id) {
  23406. return this.skeletons[index];
  23407. }
  23408. }
  23409. return null;
  23410. };
  23411. Scene.prototype.getSkeletonByName = function (name) {
  23412. for (var index = 0; index < this.skeletons.length; index++) {
  23413. if (this.skeletons[index].name === name) {
  23414. return this.skeletons[index];
  23415. }
  23416. }
  23417. return null;
  23418. };
  23419. Scene.prototype.getMorphTargetManagerById = function (id) {
  23420. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23421. if (this.morphTargetManagers[index].uniqueId === id) {
  23422. return this.morphTargetManagers[index];
  23423. }
  23424. }
  23425. return null;
  23426. };
  23427. Scene.prototype.isActiveMesh = function (mesh) {
  23428. return (this._activeMeshes.indexOf(mesh) !== -1);
  23429. };
  23430. /**
  23431. * Return a the first highlight layer of the scene with a given name.
  23432. * @param name The name of the highlight layer to look for.
  23433. * @return The highlight layer if found otherwise null.
  23434. */
  23435. Scene.prototype.getHighlightLayerByName = function (name) {
  23436. for (var index = 0; index < this.effectLayers.length; index++) {
  23437. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23438. return this.effectLayers[index];
  23439. }
  23440. }
  23441. return null;
  23442. };
  23443. /**
  23444. * Return a the first highlight layer of the scene with a given name.
  23445. * @param name The name of the highlight layer to look for.
  23446. * @return The highlight layer if found otherwise null.
  23447. */
  23448. Scene.prototype.getGlowLayerByName = function (name) {
  23449. for (var index = 0; index < this.effectLayers.length; index++) {
  23450. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23451. return this.effectLayers[index];
  23452. }
  23453. }
  23454. return null;
  23455. };
  23456. Object.defineProperty(Scene.prototype, "uid", {
  23457. /**
  23458. * Return a unique id as a string which can serve as an identifier for the scene
  23459. */
  23460. get: function () {
  23461. if (!this._uid) {
  23462. this._uid = BABYLON.Tools.RandomId();
  23463. }
  23464. return this._uid;
  23465. },
  23466. enumerable: true,
  23467. configurable: true
  23468. });
  23469. /**
  23470. * Add an externaly attached data from its key.
  23471. * This method call will fail and return false, if such key already exists.
  23472. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23473. * @param key the unique key that identifies the data
  23474. * @param data the data object to associate to the key for this Engine instance
  23475. * @return true if no such key were already present and the data was added successfully, false otherwise
  23476. */
  23477. Scene.prototype.addExternalData = function (key, data) {
  23478. if (!this._externalData) {
  23479. this._externalData = new BABYLON.StringDictionary();
  23480. }
  23481. return this._externalData.add(key, data);
  23482. };
  23483. /**
  23484. * Get an externaly attached data from its key
  23485. * @param key the unique key that identifies the data
  23486. * @return the associated data, if present (can be null), or undefined if not present
  23487. */
  23488. Scene.prototype.getExternalData = function (key) {
  23489. if (!this._externalData) {
  23490. return null;
  23491. }
  23492. return this._externalData.get(key);
  23493. };
  23494. /**
  23495. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23496. * @param key the unique key that identifies the data
  23497. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23498. * @return the associated data, can be null if the factory returned null.
  23499. */
  23500. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23501. if (!this._externalData) {
  23502. this._externalData = new BABYLON.StringDictionary();
  23503. }
  23504. return this._externalData.getOrAddWithFactory(key, factory);
  23505. };
  23506. /**
  23507. * Remove an externaly attached data from the Engine instance
  23508. * @param key the unique key that identifies the data
  23509. * @return true if the data was successfully removed, false if it doesn't exist
  23510. */
  23511. Scene.prototype.removeExternalData = function (key) {
  23512. return this._externalData.remove(key);
  23513. };
  23514. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23515. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23516. if (mesh.showSubMeshesBoundingBox) {
  23517. var boundingInfo = subMesh.getBoundingInfo();
  23518. if (boundingInfo !== null && boundingInfo !== undefined) {
  23519. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23520. }
  23521. }
  23522. var material = subMesh.getMaterial();
  23523. if (material !== null && material !== undefined) {
  23524. // Render targets
  23525. if (material.getRenderTargetTextures !== undefined) {
  23526. if (this._processedMaterials.indexOf(material) === -1) {
  23527. this._processedMaterials.push(material);
  23528. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23529. }
  23530. }
  23531. // Dispatch
  23532. this._activeIndices.addCount(subMesh.indexCount, false);
  23533. this._renderingManager.dispatch(subMesh, mesh, material);
  23534. }
  23535. }
  23536. };
  23537. Scene.prototype._isInIntermediateRendering = function () {
  23538. return this._intermediateRendering;
  23539. };
  23540. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23541. this._activeMeshCandidateProvider = provider;
  23542. };
  23543. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23544. return this._activeMeshCandidateProvider;
  23545. };
  23546. /**
  23547. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23548. */
  23549. Scene.prototype.freezeActiveMeshes = function () {
  23550. this._evaluateActiveMeshes();
  23551. this._activeMeshesFrozen = true;
  23552. return this;
  23553. };
  23554. /**
  23555. * Use this function to restart evaluating active meshes on every frame
  23556. */
  23557. Scene.prototype.unfreezeActiveMeshes = function () {
  23558. this._activeMeshesFrozen = false;
  23559. return this;
  23560. };
  23561. Scene.prototype._evaluateActiveMeshes = function () {
  23562. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23563. return;
  23564. }
  23565. if (!this.activeCamera) {
  23566. return;
  23567. }
  23568. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23569. this.activeCamera._activeMeshes.reset();
  23570. this._activeMeshes.reset();
  23571. this._renderingManager.reset();
  23572. this._processedMaterials.reset();
  23573. this._activeParticleSystems.reset();
  23574. this._activeSkeletons.reset();
  23575. this._softwareSkinnedMeshes.reset();
  23576. if (this._boundingBoxRenderer) {
  23577. this._boundingBoxRenderer.reset();
  23578. }
  23579. // Meshes
  23580. var meshes;
  23581. var len;
  23582. var checkIsEnabled = true;
  23583. // Determine mesh candidates
  23584. if (this._activeMeshCandidateProvider !== undefined) {
  23585. // Use _activeMeshCandidateProvider
  23586. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23587. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23588. if (meshes !== undefined) {
  23589. len = meshes.length;
  23590. }
  23591. else {
  23592. len = 0;
  23593. }
  23594. }
  23595. else if (this._selectionOctree !== undefined) {
  23596. // Octree
  23597. var selection = this._selectionOctree.select(this._frustumPlanes);
  23598. meshes = selection.data;
  23599. len = selection.length;
  23600. }
  23601. else {
  23602. // Full scene traversal
  23603. len = this.meshes.length;
  23604. meshes = this.meshes;
  23605. }
  23606. // Check each mesh
  23607. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23608. mesh = meshes[meshIndex];
  23609. if (mesh.isBlocked) {
  23610. continue;
  23611. }
  23612. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23613. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23614. continue;
  23615. }
  23616. mesh.computeWorldMatrix();
  23617. // Intersections
  23618. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23619. this._meshesForIntersections.pushNoDuplicate(mesh);
  23620. }
  23621. // Switch to current LOD
  23622. meshLOD = mesh.getLOD(this.activeCamera);
  23623. if (meshLOD === undefined || meshLOD === null) {
  23624. continue;
  23625. }
  23626. mesh._preActivate();
  23627. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23628. this._activeMeshes.push(mesh);
  23629. this.activeCamera._activeMeshes.push(mesh);
  23630. mesh._activate(this._renderId);
  23631. if (meshLOD !== mesh) {
  23632. meshLOD._activate(this._renderId);
  23633. }
  23634. this._activeMesh(mesh, meshLOD);
  23635. }
  23636. }
  23637. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23638. // Particle systems
  23639. if (this.particlesEnabled) {
  23640. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23641. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23642. var particleSystem = this.particleSystems[particleIndex];
  23643. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23644. continue;
  23645. }
  23646. var emitter = particleSystem.emitter;
  23647. if (!emitter.position || emitter.isEnabled()) {
  23648. this._activeParticleSystems.push(particleSystem);
  23649. particleSystem.animate();
  23650. this._renderingManager.dispatchParticles(particleSystem);
  23651. }
  23652. }
  23653. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23654. }
  23655. };
  23656. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23657. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23658. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23659. mesh.skeleton.prepare();
  23660. }
  23661. if (!mesh.computeBonesUsingShaders) {
  23662. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23663. }
  23664. }
  23665. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23666. var boundingInfo = sourceMesh.getBoundingInfo();
  23667. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23668. }
  23669. if (mesh !== undefined && mesh !== null
  23670. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23671. // Submeshes Octrees
  23672. var len;
  23673. var subMeshes;
  23674. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23675. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23676. len = intersections.length;
  23677. subMeshes = intersections.data;
  23678. }
  23679. else {
  23680. subMeshes = mesh.subMeshes;
  23681. len = subMeshes.length;
  23682. }
  23683. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23684. subMesh = subMeshes[subIndex];
  23685. this._evaluateSubMesh(subMesh, mesh);
  23686. }
  23687. }
  23688. };
  23689. Scene.prototype.updateTransformMatrix = function (force) {
  23690. if (!this.activeCamera) {
  23691. return;
  23692. }
  23693. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23694. };
  23695. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23696. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23697. };
  23698. Scene.prototype._renderForCamera = function (camera, rigParent) {
  23699. if (camera && camera._skipRendering) {
  23700. return;
  23701. }
  23702. var engine = this._engine;
  23703. this.activeCamera = camera;
  23704. if (!this.activeCamera)
  23705. throw new Error("Active camera not set");
  23706. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23707. // Viewport
  23708. engine.setViewport(this.activeCamera.viewport);
  23709. // Camera
  23710. this.resetCachedMaterial();
  23711. this._renderId++;
  23712. this.activeCamera.update();
  23713. this.updateTransformMatrix();
  23714. if (camera._alternateCamera) {
  23715. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23716. this._alternateRendering = true;
  23717. }
  23718. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23719. // Meshes
  23720. this._evaluateActiveMeshes();
  23721. // Software skinning
  23722. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23723. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23724. mesh.applySkeleton(mesh.skeleton);
  23725. }
  23726. // Render targets
  23727. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23728. var needsRestoreFrameBuffer = false;
  23729. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23730. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23731. }
  23732. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  23733. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  23734. }
  23735. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23736. this._intermediateRendering = true;
  23737. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23738. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  23739. var renderTarget = this._renderTargets.data[renderIndex];
  23740. if (renderTarget._shouldRender()) {
  23741. this._renderId++;
  23742. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  23743. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  23744. }
  23745. }
  23746. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23747. this._intermediateRendering = false;
  23748. this._renderId++;
  23749. needsRestoreFrameBuffer = true; // Restore back buffer
  23750. }
  23751. // Render EffecttLayer Texture
  23752. var stencilState = this._engine.getStencilBuffer();
  23753. var renderEffects = false;
  23754. var needStencil = false;
  23755. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  23756. this._intermediateRendering = true;
  23757. for (var i = 0; i < this.effectLayers.length; i++) {
  23758. var effectLayer = this.effectLayers[i];
  23759. if (effectLayer.shouldRender() &&
  23760. (!effectLayer.camera ||
  23761. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  23762. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  23763. renderEffects = true;
  23764. needStencil = needStencil || effectLayer.needStencil();
  23765. var renderTarget = effectLayer._mainTexture;
  23766. if (renderTarget._shouldRender()) {
  23767. this._renderId++;
  23768. renderTarget.render(false, false);
  23769. needsRestoreFrameBuffer = true;
  23770. }
  23771. }
  23772. }
  23773. this._intermediateRendering = false;
  23774. this._renderId++;
  23775. }
  23776. if (needsRestoreFrameBuffer) {
  23777. engine.restoreDefaultFramebuffer(); // Restore back buffer
  23778. }
  23779. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23780. // Prepare Frame
  23781. this.postProcessManager._prepareFrame();
  23782. // Backgrounds
  23783. var layerIndex;
  23784. var layer;
  23785. if (this.layers.length) {
  23786. engine.setDepthBuffer(false);
  23787. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23788. layer = this.layers[layerIndex];
  23789. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23790. layer.render();
  23791. }
  23792. }
  23793. engine.setDepthBuffer(true);
  23794. }
  23795. // Activate effect Layer stencil
  23796. if (needStencil) {
  23797. this._engine.setStencilBuffer(true);
  23798. }
  23799. // Render
  23800. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  23801. this._renderingManager.render(null, null, true, true);
  23802. this.onAfterDrawPhaseObservable.notifyObservers(this);
  23803. // Restore effect Layer stencil
  23804. if (needStencil) {
  23805. this._engine.setStencilBuffer(stencilState);
  23806. }
  23807. // Bounding boxes
  23808. if (this._boundingBoxRenderer) {
  23809. this._boundingBoxRenderer.render();
  23810. }
  23811. // Lens flares
  23812. if (this.lensFlaresEnabled) {
  23813. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23814. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  23815. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  23816. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  23817. lensFlareSystem.render();
  23818. }
  23819. }
  23820. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23821. }
  23822. // Foregrounds
  23823. if (this.layers.length) {
  23824. engine.setDepthBuffer(false);
  23825. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23826. layer = this.layers[layerIndex];
  23827. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23828. layer.render();
  23829. }
  23830. }
  23831. engine.setDepthBuffer(true);
  23832. }
  23833. // Effect Layer
  23834. if (renderEffects) {
  23835. engine.setDepthBuffer(false);
  23836. for (var i = 0; i < this.effectLayers.length; i++) {
  23837. if (this.effectLayers[i].shouldRender()) {
  23838. this.effectLayers[i].render();
  23839. }
  23840. }
  23841. engine.setDepthBuffer(true);
  23842. }
  23843. // Finalize frame
  23844. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  23845. // Reset some special arrays
  23846. this._renderTargets.reset();
  23847. this._alternateRendering = false;
  23848. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  23849. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23850. };
  23851. Scene.prototype._processSubCameras = function (camera) {
  23852. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  23853. this._renderForCamera(camera);
  23854. return;
  23855. }
  23856. // Update camera
  23857. if (this.activeCamera) {
  23858. this.activeCamera.update();
  23859. }
  23860. // rig cameras
  23861. for (var index = 0; index < camera._rigCameras.length; index++) {
  23862. this._renderForCamera(camera._rigCameras[index], camera);
  23863. }
  23864. this.activeCamera = camera;
  23865. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  23866. };
  23867. Scene.prototype._checkIntersections = function () {
  23868. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  23869. var sourceMesh = this._meshesForIntersections.data[index];
  23870. if (!sourceMesh.actionManager) {
  23871. continue;
  23872. }
  23873. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  23874. var action = sourceMesh.actionManager.actions[actionIndex];
  23875. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23876. var parameters = action.getTriggerParameter();
  23877. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  23878. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  23879. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  23880. if (areIntersecting && currentIntersectionInProgress === -1) {
  23881. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  23882. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23883. sourceMesh._intersectionsInProgress.push(otherMesh);
  23884. }
  23885. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23886. sourceMesh._intersectionsInProgress.push(otherMesh);
  23887. }
  23888. }
  23889. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  23890. //They intersected, and now they don't.
  23891. //is this trigger an exit trigger? execute an event.
  23892. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23893. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23894. }
  23895. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  23896. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23897. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  23898. }
  23899. }
  23900. }
  23901. }
  23902. }
  23903. };
  23904. Scene.prototype.render = function () {
  23905. if (this.isDisposed) {
  23906. return;
  23907. }
  23908. this._activeParticles.fetchNewFrame();
  23909. this._totalVertices.fetchNewFrame();
  23910. this._activeIndices.fetchNewFrame();
  23911. this._activeBones.fetchNewFrame();
  23912. this._meshesForIntersections.reset();
  23913. this.resetCachedMaterial();
  23914. this.onBeforeAnimationsObservable.notifyObservers(this);
  23915. // Actions
  23916. if (this.actionManager) {
  23917. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  23918. }
  23919. //Simplification Queue
  23920. if (this.simplificationQueue && !this.simplificationQueue.running) {
  23921. this.simplificationQueue.executeNext();
  23922. }
  23923. if (this._engine.isDeterministicLockStep()) {
  23924. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  23925. var defaultFPS = (60.0 / 1000.0);
  23926. var defaultFrameTime = 1000 / 60; // frame time in MS
  23927. if (this._physicsEngine) {
  23928. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  23929. }
  23930. var stepsTaken = 0;
  23931. var maxSubSteps = this._engine.getLockstepMaxSteps();
  23932. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  23933. internalSteps = Math.min(internalSteps, maxSubSteps);
  23934. do {
  23935. this.onBeforeStepObservable.notifyObservers(this);
  23936. // Animations
  23937. this._animationRatio = defaultFrameTime * defaultFPS;
  23938. this._animate();
  23939. this.onAfterAnimationsObservable.notifyObservers(this);
  23940. // Physics
  23941. if (this._physicsEngine) {
  23942. this.onBeforePhysicsObservable.notifyObservers(this);
  23943. this._physicsEngine._step(defaultFrameTime / 1000);
  23944. this.onAfterPhysicsObservable.notifyObservers(this);
  23945. }
  23946. this.onAfterStepObservable.notifyObservers(this);
  23947. this._currentStepId++;
  23948. stepsTaken++;
  23949. deltaTime -= defaultFrameTime;
  23950. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23951. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23952. }
  23953. else {
  23954. // Animations
  23955. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23956. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23957. this._animate();
  23958. this.onAfterAnimationsObservable.notifyObservers(this);
  23959. // Physics
  23960. if (this._physicsEngine) {
  23961. this.onBeforePhysicsObservable.notifyObservers(this);
  23962. this._physicsEngine._step(deltaTime / 1000.0);
  23963. this.onAfterPhysicsObservable.notifyObservers(this);
  23964. }
  23965. }
  23966. // update gamepad manager
  23967. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23968. this._gamepadManager._checkGamepadsStatus();
  23969. }
  23970. // Before render
  23971. this.onBeforeRenderObservable.notifyObservers(this);
  23972. // Customs render targets
  23973. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23974. var engine = this.getEngine();
  23975. var currentActiveCamera = this.activeCamera;
  23976. if (this.renderTargetsEnabled) {
  23977. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23978. this._intermediateRendering = true;
  23979. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23980. var renderTarget = this.customRenderTargets[customIndex];
  23981. if (renderTarget._shouldRender()) {
  23982. this._renderId++;
  23983. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23984. if (!this.activeCamera)
  23985. throw new Error("Active camera not set");
  23986. // Viewport
  23987. engine.setViewport(this.activeCamera.viewport);
  23988. // Camera
  23989. this.updateTransformMatrix();
  23990. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23991. }
  23992. }
  23993. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23994. this._intermediateRendering = false;
  23995. this._renderId++;
  23996. }
  23997. // Restore back buffer
  23998. if (this.customRenderTargets.length > 0) {
  23999. engine.restoreDefaultFramebuffer();
  24000. }
  24001. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24002. this.activeCamera = currentActiveCamera;
  24003. // Procedural textures
  24004. if (this.proceduralTexturesEnabled) {
  24005. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24006. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24007. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24008. if (proceduralTexture._shouldRender()) {
  24009. proceduralTexture.render();
  24010. }
  24011. }
  24012. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24013. }
  24014. // Clear
  24015. if (this.autoClearDepthAndStencil || this.autoClear) {
  24016. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24017. }
  24018. // Shadows
  24019. if (this.shadowsEnabled) {
  24020. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24021. var light = this.lights[lightIndex];
  24022. var shadowGenerator = light.getShadowGenerator();
  24023. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24024. var shadowMap = (shadowGenerator.getShadowMap());
  24025. if (this.textures.indexOf(shadowMap) !== -1) {
  24026. this._renderTargets.push(shadowMap);
  24027. }
  24028. }
  24029. }
  24030. }
  24031. // Depth renderer
  24032. if (this._depthRenderer) {
  24033. this._renderTargets.push(this._depthRenderer.getDepthMap());
  24034. }
  24035. // Geometry renderer
  24036. if (this._geometryBufferRenderer) {
  24037. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24038. }
  24039. // RenderPipeline
  24040. if (this._postProcessRenderPipelineManager) {
  24041. this._postProcessRenderPipelineManager.update();
  24042. }
  24043. // Multi-cameras?
  24044. if (this.activeCameras.length > 0) {
  24045. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24046. if (cameraIndex > 0) {
  24047. this._engine.clear(null, false, true, true);
  24048. }
  24049. this._processSubCameras(this.activeCameras[cameraIndex]);
  24050. }
  24051. }
  24052. else {
  24053. if (!this.activeCamera) {
  24054. throw new Error("No camera defined");
  24055. }
  24056. this._processSubCameras(this.activeCamera);
  24057. }
  24058. // Intersection checks
  24059. this._checkIntersections();
  24060. // Update the audio listener attached to the camera
  24061. if (BABYLON.AudioEngine) {
  24062. this._updateAudioParameters();
  24063. }
  24064. // After render
  24065. if (this.afterRender) {
  24066. this.afterRender();
  24067. }
  24068. this.onAfterRenderObservable.notifyObservers(this);
  24069. // Cleaning
  24070. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24071. var data = this._toBeDisposed.data[index];
  24072. if (data) {
  24073. data.dispose();
  24074. }
  24075. this._toBeDisposed[index] = null;
  24076. }
  24077. this._toBeDisposed.reset();
  24078. if (this.dumpNextRenderTargets) {
  24079. this.dumpNextRenderTargets = false;
  24080. }
  24081. this._activeBones.addCount(0, true);
  24082. this._activeIndices.addCount(0, true);
  24083. this._activeParticles.addCount(0, true);
  24084. };
  24085. Scene.prototype._updateAudioParameters = function () {
  24086. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24087. return;
  24088. }
  24089. var listeningCamera;
  24090. var audioEngine = BABYLON.Engine.audioEngine;
  24091. if (this.activeCameras.length > 0) {
  24092. listeningCamera = this.activeCameras[0];
  24093. }
  24094. else {
  24095. listeningCamera = this.activeCamera;
  24096. }
  24097. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24098. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24099. // for VR cameras
  24100. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24101. listeningCamera = listeningCamera.rigCameras[0];
  24102. }
  24103. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24104. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24105. cameraDirection.normalize();
  24106. // To avoid some errors on GearVR
  24107. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24108. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24109. }
  24110. var i;
  24111. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24112. var sound = this.mainSoundTrack.soundCollection[i];
  24113. if (sound.useCustomAttenuation) {
  24114. sound.updateDistanceFromListener();
  24115. }
  24116. }
  24117. for (i = 0; i < this.soundTracks.length; i++) {
  24118. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24119. sound = this.soundTracks[i].soundCollection[j];
  24120. if (sound.useCustomAttenuation) {
  24121. sound.updateDistanceFromListener();
  24122. }
  24123. }
  24124. }
  24125. }
  24126. };
  24127. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24128. // Audio
  24129. get: function () {
  24130. return this._audioEnabled;
  24131. },
  24132. set: function (value) {
  24133. this._audioEnabled = value;
  24134. if (BABYLON.AudioEngine) {
  24135. if (this._audioEnabled) {
  24136. this._enableAudio();
  24137. }
  24138. else {
  24139. this._disableAudio();
  24140. }
  24141. }
  24142. },
  24143. enumerable: true,
  24144. configurable: true
  24145. });
  24146. Scene.prototype._disableAudio = function () {
  24147. var i;
  24148. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24149. this.mainSoundTrack.soundCollection[i].pause();
  24150. }
  24151. for (i = 0; i < this.soundTracks.length; i++) {
  24152. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24153. this.soundTracks[i].soundCollection[j].pause();
  24154. }
  24155. }
  24156. };
  24157. Scene.prototype._enableAudio = function () {
  24158. var i;
  24159. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24160. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24161. this.mainSoundTrack.soundCollection[i].play();
  24162. }
  24163. }
  24164. for (i = 0; i < this.soundTracks.length; i++) {
  24165. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24166. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24167. this.soundTracks[i].soundCollection[j].play();
  24168. }
  24169. }
  24170. }
  24171. };
  24172. Object.defineProperty(Scene.prototype, "headphone", {
  24173. get: function () {
  24174. return this._headphone;
  24175. },
  24176. set: function (value) {
  24177. this._headphone = value;
  24178. if (BABYLON.AudioEngine) {
  24179. if (this._headphone) {
  24180. this._switchAudioModeForHeadphones();
  24181. }
  24182. else {
  24183. this._switchAudioModeForNormalSpeakers();
  24184. }
  24185. }
  24186. },
  24187. enumerable: true,
  24188. configurable: true
  24189. });
  24190. Scene.prototype._switchAudioModeForHeadphones = function () {
  24191. this.mainSoundTrack.switchPanningModelToHRTF();
  24192. for (var i = 0; i < this.soundTracks.length; i++) {
  24193. this.soundTracks[i].switchPanningModelToHRTF();
  24194. }
  24195. };
  24196. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24197. this.mainSoundTrack.switchPanningModelToEqualPower();
  24198. for (var i = 0; i < this.soundTracks.length; i++) {
  24199. this.soundTracks[i].switchPanningModelToEqualPower();
  24200. }
  24201. };
  24202. Scene.prototype.enableDepthRenderer = function () {
  24203. if (this._depthRenderer) {
  24204. return this._depthRenderer;
  24205. }
  24206. this._depthRenderer = new BABYLON.DepthRenderer(this);
  24207. return this._depthRenderer;
  24208. };
  24209. Scene.prototype.disableDepthRenderer = function () {
  24210. if (!this._depthRenderer) {
  24211. return;
  24212. }
  24213. this._depthRenderer.dispose();
  24214. this._depthRenderer = null;
  24215. };
  24216. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24217. if (ratio === void 0) { ratio = 1; }
  24218. if (this._geometryBufferRenderer) {
  24219. return this._geometryBufferRenderer;
  24220. }
  24221. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24222. if (!this._geometryBufferRenderer.isSupported) {
  24223. this._geometryBufferRenderer = null;
  24224. }
  24225. return this._geometryBufferRenderer;
  24226. };
  24227. Scene.prototype.disableGeometryBufferRenderer = function () {
  24228. if (!this._geometryBufferRenderer) {
  24229. return;
  24230. }
  24231. this._geometryBufferRenderer.dispose();
  24232. this._geometryBufferRenderer = null;
  24233. };
  24234. Scene.prototype.freezeMaterials = function () {
  24235. for (var i = 0; i < this.materials.length; i++) {
  24236. this.materials[i].freeze();
  24237. }
  24238. };
  24239. Scene.prototype.unfreezeMaterials = function () {
  24240. for (var i = 0; i < this.materials.length; i++) {
  24241. this.materials[i].unfreeze();
  24242. }
  24243. };
  24244. Scene.prototype.dispose = function () {
  24245. this.beforeRender = null;
  24246. this.afterRender = null;
  24247. this.skeletons = [];
  24248. this.morphTargetManagers = [];
  24249. this.importedMeshesFiles = new Array();
  24250. this.stopAllAnimations();
  24251. this.resetCachedMaterial();
  24252. if (this._depthRenderer) {
  24253. this._depthRenderer.dispose();
  24254. }
  24255. if (this._gamepadManager) {
  24256. this._gamepadManager.dispose();
  24257. this._gamepadManager = null;
  24258. }
  24259. // Smart arrays
  24260. if (this.activeCamera) {
  24261. this.activeCamera._activeMeshes.dispose();
  24262. this.activeCamera = null;
  24263. }
  24264. this._activeMeshes.dispose();
  24265. this._renderingManager.dispose();
  24266. this._processedMaterials.dispose();
  24267. this._activeParticleSystems.dispose();
  24268. this._activeSkeletons.dispose();
  24269. this._softwareSkinnedMeshes.dispose();
  24270. this._renderTargets.dispose();
  24271. if (this._boundingBoxRenderer) {
  24272. this._boundingBoxRenderer.dispose();
  24273. }
  24274. this._meshesForIntersections.dispose();
  24275. this._toBeDisposed.dispose();
  24276. // Abort active requests
  24277. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24278. var request = _a[_i];
  24279. request.abort();
  24280. }
  24281. // Debug layer
  24282. if (this._debugLayer) {
  24283. this._debugLayer.hide();
  24284. }
  24285. // Events
  24286. this.onDisposeObservable.notifyObservers(this);
  24287. this.onDisposeObservable.clear();
  24288. this.onBeforeRenderObservable.clear();
  24289. this.onAfterRenderObservable.clear();
  24290. this.OnBeforeRenderTargetsRenderObservable.clear();
  24291. this.OnAfterRenderTargetsRenderObservable.clear();
  24292. this.onAfterStepObservable.clear();
  24293. this.onBeforeStepObservable.clear();
  24294. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24295. this.onAfterActiveMeshesEvaluationObservable.clear();
  24296. this.onBeforeParticlesRenderingObservable.clear();
  24297. this.onAfterParticlesRenderingObservable.clear();
  24298. this.onBeforeSpritesRenderingObservable.clear();
  24299. this.onAfterSpritesRenderingObservable.clear();
  24300. this.onBeforeDrawPhaseObservable.clear();
  24301. this.onAfterDrawPhaseObservable.clear();
  24302. this.onBeforePhysicsObservable.clear();
  24303. this.onAfterPhysicsObservable.clear();
  24304. this.onBeforeAnimationsObservable.clear();
  24305. this.onAfterAnimationsObservable.clear();
  24306. this.onDataLoadedObservable.clear();
  24307. this.detachControl();
  24308. // Release sounds & sounds tracks
  24309. if (BABYLON.AudioEngine) {
  24310. this.disposeSounds();
  24311. }
  24312. // VR Helper
  24313. if (this.VRHelper) {
  24314. this.VRHelper.dispose();
  24315. }
  24316. // Detach cameras
  24317. var canvas = this._engine.getRenderingCanvas();
  24318. if (canvas) {
  24319. var index;
  24320. for (index = 0; index < this.cameras.length; index++) {
  24321. this.cameras[index].detachControl(canvas);
  24322. }
  24323. }
  24324. // Release animation groups
  24325. while (this.animationGroups.length) {
  24326. this.animationGroups[0].dispose();
  24327. }
  24328. // Release lights
  24329. while (this.lights.length) {
  24330. this.lights[0].dispose();
  24331. }
  24332. // Release meshes
  24333. while (this.meshes.length) {
  24334. this.meshes[0].dispose(true);
  24335. }
  24336. while (this.transformNodes.length) {
  24337. this.removeTransformNode(this.transformNodes[0]);
  24338. }
  24339. // Release cameras
  24340. while (this.cameras.length) {
  24341. this.cameras[0].dispose();
  24342. }
  24343. // Release materials
  24344. if (this.defaultMaterial) {
  24345. this.defaultMaterial.dispose();
  24346. }
  24347. while (this.multiMaterials.length) {
  24348. this.multiMaterials[0].dispose();
  24349. }
  24350. while (this.materials.length) {
  24351. this.materials[0].dispose();
  24352. }
  24353. // Release particles
  24354. while (this.particleSystems.length) {
  24355. this.particleSystems[0].dispose();
  24356. }
  24357. // Release sprites
  24358. while (this.spriteManagers.length) {
  24359. this.spriteManagers[0].dispose();
  24360. }
  24361. // Release postProcesses
  24362. while (this.postProcesses.length) {
  24363. this.postProcesses[0].dispose();
  24364. }
  24365. // Release layers
  24366. while (this.layers.length) {
  24367. this.layers[0].dispose();
  24368. }
  24369. while (this.effectLayers.length) {
  24370. this.effectLayers[0].dispose();
  24371. }
  24372. // Release textures
  24373. while (this.textures.length) {
  24374. this.textures[0].dispose();
  24375. }
  24376. // Release UBO
  24377. this._sceneUbo.dispose();
  24378. if (this._alternateSceneUbo) {
  24379. this._alternateSceneUbo.dispose();
  24380. }
  24381. // Post-processes
  24382. this.postProcessManager.dispose();
  24383. if (this._postProcessRenderPipelineManager) {
  24384. this._postProcessRenderPipelineManager.dispose();
  24385. }
  24386. // Physics
  24387. if (this._physicsEngine) {
  24388. this.disablePhysicsEngine();
  24389. }
  24390. // Remove from engine
  24391. index = this._engine.scenes.indexOf(this);
  24392. if (index > -1) {
  24393. this._engine.scenes.splice(index, 1);
  24394. }
  24395. this._engine.wipeCaches(true);
  24396. this._isDisposed = true;
  24397. };
  24398. Object.defineProperty(Scene.prototype, "isDisposed", {
  24399. get: function () {
  24400. return this._isDisposed;
  24401. },
  24402. enumerable: true,
  24403. configurable: true
  24404. });
  24405. // Release sounds & sounds tracks
  24406. Scene.prototype.disposeSounds = function () {
  24407. if (!this._mainSoundTrack) {
  24408. return;
  24409. }
  24410. this.mainSoundTrack.dispose();
  24411. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24412. this.soundTracks[scIndex].dispose();
  24413. }
  24414. };
  24415. // Octrees
  24416. /**
  24417. * Get the world extend vectors with an optional filter
  24418. *
  24419. * @param {(mesh: AbstractMesh) => boolean} [filterPredicate] the predicate - which meshes should be included when calculating the world size
  24420. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24421. */
  24422. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24423. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24424. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24425. filterPredicate = filterPredicate || (function () { return true; });
  24426. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24427. mesh.computeWorldMatrix(true);
  24428. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24429. return;
  24430. }
  24431. var boundingInfo = mesh.getBoundingInfo();
  24432. var minBox = boundingInfo.boundingBox.minimumWorld;
  24433. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24434. BABYLON.Tools.CheckExtends(minBox, min, max);
  24435. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24436. });
  24437. return {
  24438. min: min,
  24439. max: max
  24440. };
  24441. };
  24442. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24443. if (maxCapacity === void 0) { maxCapacity = 64; }
  24444. if (maxDepth === void 0) { maxDepth = 2; }
  24445. if (!this._selectionOctree) {
  24446. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24447. }
  24448. var worldExtends = this.getWorldExtends();
  24449. // Update octree
  24450. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24451. return this._selectionOctree;
  24452. };
  24453. // Picking
  24454. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24455. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24456. var result = BABYLON.Ray.Zero();
  24457. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24458. return result;
  24459. };
  24460. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24461. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24462. var engine = this._engine;
  24463. if (!camera) {
  24464. if (!this.activeCamera)
  24465. throw new Error("Active camera not set");
  24466. camera = this.activeCamera;
  24467. }
  24468. var cameraViewport = camera.viewport;
  24469. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24470. // Moving coordinates to local viewport world
  24471. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24472. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24473. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24474. return this;
  24475. };
  24476. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24477. var result = BABYLON.Ray.Zero();
  24478. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24479. return result;
  24480. };
  24481. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24482. if (!BABYLON.PickingInfo) {
  24483. return this;
  24484. }
  24485. var engine = this._engine;
  24486. if (!camera) {
  24487. if (!this.activeCamera)
  24488. throw new Error("Active camera not set");
  24489. camera = this.activeCamera;
  24490. }
  24491. var cameraViewport = camera.viewport;
  24492. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24493. var identity = BABYLON.Matrix.Identity();
  24494. // Moving coordinates to local viewport world
  24495. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24496. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24497. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24498. return this;
  24499. };
  24500. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24501. if (!BABYLON.PickingInfo) {
  24502. return null;
  24503. }
  24504. var pickingInfo = null;
  24505. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24506. var mesh = this.meshes[meshIndex];
  24507. if (predicate) {
  24508. if (!predicate(mesh)) {
  24509. continue;
  24510. }
  24511. }
  24512. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24513. continue;
  24514. }
  24515. var world = mesh.getWorldMatrix();
  24516. var ray = rayFunction(world);
  24517. var result = mesh.intersects(ray, fastCheck);
  24518. if (!result || !result.hit)
  24519. continue;
  24520. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24521. continue;
  24522. pickingInfo = result;
  24523. if (fastCheck) {
  24524. break;
  24525. }
  24526. }
  24527. return pickingInfo || new BABYLON.PickingInfo();
  24528. };
  24529. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24530. if (!BABYLON.PickingInfo) {
  24531. return null;
  24532. }
  24533. var pickingInfos = new Array();
  24534. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24535. var mesh = this.meshes[meshIndex];
  24536. if (predicate) {
  24537. if (!predicate(mesh)) {
  24538. continue;
  24539. }
  24540. }
  24541. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24542. continue;
  24543. }
  24544. var world = mesh.getWorldMatrix();
  24545. var ray = rayFunction(world);
  24546. var result = mesh.intersects(ray, false);
  24547. if (!result || !result.hit)
  24548. continue;
  24549. pickingInfos.push(result);
  24550. }
  24551. return pickingInfos;
  24552. };
  24553. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24554. if (!BABYLON.PickingInfo) {
  24555. return null;
  24556. }
  24557. var pickingInfo = null;
  24558. if (!camera) {
  24559. if (!this.activeCamera) {
  24560. return null;
  24561. }
  24562. camera = this.activeCamera;
  24563. }
  24564. if (this.spriteManagers.length > 0) {
  24565. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24566. var spriteManager = this.spriteManagers[spriteIndex];
  24567. if (!spriteManager.isPickable) {
  24568. continue;
  24569. }
  24570. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24571. if (!result || !result.hit)
  24572. continue;
  24573. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24574. continue;
  24575. pickingInfo = result;
  24576. if (fastCheck) {
  24577. break;
  24578. }
  24579. }
  24580. }
  24581. return pickingInfo || new BABYLON.PickingInfo();
  24582. };
  24583. /** Launch a ray to try to pick a mesh in the scene
  24584. * @param x position on screen
  24585. * @param y position on screen
  24586. * @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
  24587. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24588. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24589. */
  24590. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24591. var _this = this;
  24592. if (!BABYLON.PickingInfo) {
  24593. return null;
  24594. }
  24595. return this._internalPick(function (world) {
  24596. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24597. return _this._tempPickingRay;
  24598. }, predicate, fastCheck);
  24599. };
  24600. /** Launch a ray to try to pick a sprite in the scene
  24601. * @param x position on screen
  24602. * @param y position on screen
  24603. * @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
  24604. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24605. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24606. */
  24607. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24608. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24609. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24610. };
  24611. /** Use the given ray to pick a mesh in the scene
  24612. * @param ray The ray to use to pick meshes
  24613. * @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
  24614. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24615. */
  24616. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24617. var _this = this;
  24618. return this._internalPick(function (world) {
  24619. if (!_this._pickWithRayInverseMatrix) {
  24620. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24621. }
  24622. world.invertToRef(_this._pickWithRayInverseMatrix);
  24623. if (!_this._cachedRayForTransform) {
  24624. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24625. }
  24626. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24627. return _this._cachedRayForTransform;
  24628. }, predicate, fastCheck);
  24629. };
  24630. /**
  24631. * Launch a ray to try to pick a mesh in the scene
  24632. * @param x X position on screen
  24633. * @param y Y position on screen
  24634. * @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
  24635. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24636. */
  24637. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24638. var _this = this;
  24639. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24640. };
  24641. /**
  24642. * Launch a ray to try to pick a mesh in the scene
  24643. * @param ray Ray to use
  24644. * @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
  24645. */
  24646. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24647. var _this = this;
  24648. return this._internalMultiPick(function (world) {
  24649. if (!_this._pickWithRayInverseMatrix) {
  24650. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24651. }
  24652. world.invertToRef(_this._pickWithRayInverseMatrix);
  24653. if (!_this._cachedRayForTransform) {
  24654. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24655. }
  24656. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24657. return _this._cachedRayForTransform;
  24658. }, predicate);
  24659. };
  24660. Scene.prototype.setPointerOverMesh = function (mesh) {
  24661. if (this._pointerOverMesh === mesh) {
  24662. return;
  24663. }
  24664. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24665. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24666. }
  24667. this._pointerOverMesh = mesh;
  24668. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24669. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24670. }
  24671. };
  24672. Scene.prototype.getPointerOverMesh = function () {
  24673. return this._pointerOverMesh;
  24674. };
  24675. Scene.prototype.setPointerOverSprite = function (sprite) {
  24676. if (this._pointerOverSprite === sprite) {
  24677. return;
  24678. }
  24679. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24680. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24681. }
  24682. this._pointerOverSprite = sprite;
  24683. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24684. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24685. }
  24686. };
  24687. Scene.prototype.getPointerOverSprite = function () {
  24688. return this._pointerOverSprite;
  24689. };
  24690. // Physics
  24691. Scene.prototype.getPhysicsEngine = function () {
  24692. return this._physicsEngine;
  24693. };
  24694. /**
  24695. * Enables physics to the current scene
  24696. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24697. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24698. * @return {boolean} was the physics engine initialized
  24699. */
  24700. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24701. if (gravity === void 0) { gravity = null; }
  24702. if (this._physicsEngine) {
  24703. return true;
  24704. }
  24705. try {
  24706. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24707. return true;
  24708. }
  24709. catch (e) {
  24710. BABYLON.Tools.Error(e.message);
  24711. return false;
  24712. }
  24713. };
  24714. Scene.prototype.disablePhysicsEngine = function () {
  24715. if (!this._physicsEngine) {
  24716. return;
  24717. }
  24718. this._physicsEngine.dispose();
  24719. this._physicsEngine = null;
  24720. };
  24721. Scene.prototype.isPhysicsEnabled = function () {
  24722. return this._physicsEngine !== undefined;
  24723. };
  24724. Scene.prototype.deleteCompoundImpostor = function (compound) {
  24725. var mesh = compound.parts[0].mesh;
  24726. if (mesh.physicsImpostor) {
  24727. mesh.physicsImpostor.dispose();
  24728. mesh.physicsImpostor = null;
  24729. }
  24730. };
  24731. // Misc.
  24732. Scene.prototype._rebuildGeometries = function () {
  24733. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  24734. var geometry = _a[_i];
  24735. geometry._rebuild();
  24736. }
  24737. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  24738. var mesh = _c[_b];
  24739. mesh._rebuild();
  24740. }
  24741. if (this.postProcessManager) {
  24742. this.postProcessManager._rebuild();
  24743. }
  24744. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  24745. var layer = _e[_d];
  24746. layer._rebuild();
  24747. }
  24748. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  24749. var effectLayer = _g[_f];
  24750. effectLayer._rebuild();
  24751. }
  24752. if (this._boundingBoxRenderer) {
  24753. this._boundingBoxRenderer._rebuild();
  24754. }
  24755. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  24756. var system = _j[_h];
  24757. system.rebuild();
  24758. }
  24759. if (this._postProcessRenderPipelineManager) {
  24760. this._postProcessRenderPipelineManager._rebuild();
  24761. }
  24762. };
  24763. Scene.prototype._rebuildTextures = function () {
  24764. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  24765. var texture = _a[_i];
  24766. texture._rebuild();
  24767. }
  24768. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24769. };
  24770. /**
  24771. * Creates a default light for the scene.
  24772. * @param replace Whether to replace the existing lights in the scene.
  24773. */
  24774. Scene.prototype.createDefaultLight = function (replace) {
  24775. if (replace === void 0) { replace = false; }
  24776. // Dispose existing light in replace mode.
  24777. if (replace) {
  24778. if (this.lights) {
  24779. for (var i = 0; i < this.lights.length; i++) {
  24780. this.lights[i].dispose();
  24781. }
  24782. }
  24783. }
  24784. // Light
  24785. if (this.lights.length === 0) {
  24786. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  24787. }
  24788. };
  24789. /**
  24790. * Creates a default camera for the scene.
  24791. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  24792. * @param replace Whether to replace the existing active camera in the scene.
  24793. * @param attachCameraControls Whether to attach camera controls to the canvas.
  24794. */
  24795. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  24796. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24797. if (replace === void 0) { replace = false; }
  24798. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24799. // Dispose existing camera in replace mode.
  24800. if (replace) {
  24801. if (this.activeCamera) {
  24802. this.activeCamera.dispose();
  24803. this.activeCamera = null;
  24804. }
  24805. }
  24806. // Camera
  24807. if (!this.activeCamera) {
  24808. var worldExtends = this.getWorldExtends();
  24809. var worldSize = worldExtends.max.subtract(worldExtends.min);
  24810. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  24811. var camera;
  24812. var radius = worldSize.length() * 1.5;
  24813. // empty scene scenario!
  24814. if (!isFinite(radius)) {
  24815. radius = 1;
  24816. worldCenter.copyFromFloats(0, 0, 0);
  24817. }
  24818. if (createArcRotateCamera) {
  24819. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  24820. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  24821. arcRotateCamera.wheelPrecision = 100 / radius;
  24822. camera = arcRotateCamera;
  24823. }
  24824. else {
  24825. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  24826. freeCamera.setTarget(worldCenter);
  24827. camera = freeCamera;
  24828. }
  24829. camera.minZ = radius * 0.01;
  24830. camera.maxZ = radius * 1000;
  24831. camera.speed = radius * 0.2;
  24832. this.activeCamera = camera;
  24833. var canvas = this.getEngine().getRenderingCanvas();
  24834. if (attachCameraControls && canvas) {
  24835. camera.attachControl(canvas);
  24836. }
  24837. }
  24838. };
  24839. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  24840. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24841. if (replace === void 0) { replace = false; }
  24842. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24843. this.createDefaultLight(replace);
  24844. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  24845. };
  24846. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  24847. if (pbr === void 0) { pbr = false; }
  24848. if (scale === void 0) { scale = 1000; }
  24849. if (blur === void 0) { blur = 0; }
  24850. if (environmentTexture) {
  24851. this.environmentTexture = environmentTexture;
  24852. }
  24853. if (!this.environmentTexture) {
  24854. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  24855. return null;
  24856. }
  24857. // Skybox
  24858. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  24859. if (pbr) {
  24860. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  24861. hdrSkyboxMaterial.backFaceCulling = false;
  24862. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24863. if (hdrSkyboxMaterial.reflectionTexture) {
  24864. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24865. }
  24866. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  24867. hdrSkyboxMaterial.disableLighting = true;
  24868. hdrSkyboxMaterial.twoSidedLighting = true;
  24869. hdrSkybox.infiniteDistance = true;
  24870. hdrSkybox.material = hdrSkyboxMaterial;
  24871. }
  24872. else {
  24873. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  24874. skyboxMaterial.backFaceCulling = false;
  24875. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24876. if (skyboxMaterial.reflectionTexture) {
  24877. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24878. }
  24879. skyboxMaterial.disableLighting = true;
  24880. hdrSkybox.infiniteDistance = true;
  24881. hdrSkybox.material = skyboxMaterial;
  24882. }
  24883. return hdrSkybox;
  24884. };
  24885. Scene.prototype.createDefaultEnvironment = function (options) {
  24886. if (BABYLON.EnvironmentHelper) {
  24887. return new BABYLON.EnvironmentHelper(options, this);
  24888. }
  24889. return null;
  24890. };
  24891. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  24892. if (webVROptions === void 0) { webVROptions = {}; }
  24893. return new BABYLON.VRExperienceHelper(this, webVROptions);
  24894. };
  24895. // Tags
  24896. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  24897. if (tagsQuery === undefined) {
  24898. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  24899. return list;
  24900. }
  24901. var listByTags = [];
  24902. forEach = forEach || (function (item) { return; });
  24903. for (var i in list) {
  24904. var item = list[i];
  24905. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  24906. listByTags.push(item);
  24907. forEach(item);
  24908. }
  24909. }
  24910. return listByTags;
  24911. };
  24912. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  24913. return this._getByTags(this.meshes, tagsQuery, forEach);
  24914. };
  24915. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  24916. return this._getByTags(this.cameras, tagsQuery, forEach);
  24917. };
  24918. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  24919. return this._getByTags(this.lights, tagsQuery, forEach);
  24920. };
  24921. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  24922. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  24923. };
  24924. /**
  24925. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24926. * This allowed control for front to back rendering or reversly depending of the special needs.
  24927. *
  24928. * @param renderingGroupId The rendering group id corresponding to its index
  24929. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24930. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24931. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24932. */
  24933. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24934. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24935. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24936. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24937. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24938. };
  24939. /**
  24940. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24941. *
  24942. * @param renderingGroupId The rendering group id corresponding to its index
  24943. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24944. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24945. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24946. */
  24947. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24948. if (depth === void 0) { depth = true; }
  24949. if (stencil === void 0) { stencil = true; }
  24950. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24951. };
  24952. /**
  24953. * Will flag all materials as dirty to trigger new shader compilation
  24954. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24955. */
  24956. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24957. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24958. var material = _a[_i];
  24959. if (predicate && !predicate(material)) {
  24960. continue;
  24961. }
  24962. material.markAsDirty(flag);
  24963. }
  24964. };
  24965. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24966. var _this = this;
  24967. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24968. this._activeRequests.push(request);
  24969. request.onCompleteObservable.add(function (request) {
  24970. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24971. });
  24972. return request;
  24973. };
  24974. /** @ignore */
  24975. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24976. var _this = this;
  24977. return new Promise(function (resolve, reject) {
  24978. _this._loadFile(url, function (data) {
  24979. resolve(data);
  24980. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24981. reject(exception);
  24982. });
  24983. });
  24984. };
  24985. // Statics
  24986. Scene._FOGMODE_NONE = 0;
  24987. Scene._FOGMODE_EXP = 1;
  24988. Scene._FOGMODE_EXP2 = 2;
  24989. Scene._FOGMODE_LINEAR = 3;
  24990. Scene._uniqueIdCounter = 0;
  24991. Scene.MinDeltaTime = 1.0;
  24992. Scene.MaxDeltaTime = 1000.0;
  24993. /** The distance in pixel that you have to move to prevent some events */
  24994. Scene.DragMovementThreshold = 10; // in pixels
  24995. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24996. Scene.LongPressDelay = 500; // in milliseconds
  24997. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24998. Scene.DoubleClickDelay = 300; // in milliseconds
  24999. /** If you need to check double click without raising a single click at first click, enable this flag */
  25000. Scene.ExclusiveDoubleClickMode = false;
  25001. return Scene;
  25002. }());
  25003. BABYLON.Scene = Scene;
  25004. })(BABYLON || (BABYLON = {}));
  25005. //# sourceMappingURL=babylon.scene.js.map
  25006. var BABYLON;
  25007. (function (BABYLON) {
  25008. /**
  25009. * Set of assets to keep when moving a scene into an asset container.
  25010. */
  25011. var KeepAssets = /** @class */ (function () {
  25012. function KeepAssets() {
  25013. /**
  25014. * Cameras to keep.
  25015. */
  25016. this.cameras = new Array();
  25017. /**
  25018. * Lights to keep.
  25019. */
  25020. this.lights = new Array();
  25021. /**
  25022. * Meshes to keep.
  25023. */
  25024. this.meshes = new Array();
  25025. /**
  25026. * Skeletons to keep.
  25027. */
  25028. this.skeletons = new Array();
  25029. /**
  25030. * ParticleSystems to keep.
  25031. */
  25032. this.particleSystems = new Array();
  25033. /**
  25034. * Animations to keep.
  25035. */
  25036. this.animations = new Array();
  25037. /**
  25038. * MultiMaterials to keep.
  25039. */
  25040. this.multiMaterials = new Array();
  25041. /**
  25042. * Materials to keep.
  25043. */
  25044. this.materials = new Array();
  25045. /**
  25046. * MorphTargetManagers to keep.
  25047. */
  25048. this.morphTargetManagers = new Array();
  25049. /**
  25050. * Geometries to keep.
  25051. */
  25052. this.geometries = new Array();
  25053. /**
  25054. * TransformNodes to keep.
  25055. */
  25056. this.transformNodes = new Array();
  25057. /**
  25058. * LensFlareSystems to keep.
  25059. */
  25060. this.lensFlareSystems = new Array();
  25061. /**
  25062. * ShadowGenerators to keep.
  25063. */
  25064. this.shadowGenerators = new Array();
  25065. /**
  25066. * ActionManagers to keep.
  25067. */
  25068. this.actionManagers = new Array();
  25069. /**
  25070. * Sounds to keep.
  25071. */
  25072. this.sounds = new Array();
  25073. }
  25074. return KeepAssets;
  25075. }());
  25076. BABYLON.KeepAssets = KeepAssets;
  25077. /**
  25078. * Container with a set of assets that can be added or removed from a scene.
  25079. */
  25080. var AssetContainer = /** @class */ (function () {
  25081. /**
  25082. * Instantiates an AssetContainer.
  25083. * @param scene The scene the AssetContainer belongs to.
  25084. */
  25085. function AssetContainer(scene) {
  25086. // Objects
  25087. /**
  25088. * Cameras populated in the container.
  25089. */
  25090. this.cameras = new Array();
  25091. /**
  25092. * Lights populated in the container.
  25093. */
  25094. this.lights = new Array();
  25095. /**
  25096. * Meshes populated in the container.
  25097. */
  25098. this.meshes = new Array();
  25099. /**
  25100. * Skeletons populated in the container.
  25101. */
  25102. this.skeletons = new Array();
  25103. /**
  25104. * ParticleSystems populated in the container.
  25105. */
  25106. this.particleSystems = new Array();
  25107. /**
  25108. * Animations populated in the container.
  25109. */
  25110. this.animations = new Array();
  25111. /**
  25112. * MultiMaterials populated in the container.
  25113. */
  25114. this.multiMaterials = new Array();
  25115. /**
  25116. * Materials populated in the container.
  25117. */
  25118. this.materials = new Array();
  25119. /**
  25120. * MorphTargetManagers populated in the container.
  25121. */
  25122. this.morphTargetManagers = new Array();
  25123. /**
  25124. * Geometries populated in the container.
  25125. */
  25126. this.geometries = new Array();
  25127. /**
  25128. * TransformNodes populated in the container.
  25129. */
  25130. this.transformNodes = new Array();
  25131. /**
  25132. * LensFlareSystems populated in the container.
  25133. */
  25134. this.lensFlareSystems = new Array();
  25135. /**
  25136. * ShadowGenerators populated in the container.
  25137. */
  25138. this.shadowGenerators = new Array();
  25139. /**
  25140. * ActionManagers populated in the container.
  25141. */
  25142. this.actionManagers = new Array();
  25143. /**
  25144. * Sounds populated in the container.
  25145. */
  25146. this.sounds = new Array();
  25147. this.scene = scene;
  25148. }
  25149. /**
  25150. * Adds all the assets from the container to the scene.
  25151. */
  25152. AssetContainer.prototype.addAllToScene = function () {
  25153. var _this = this;
  25154. this.cameras.forEach(function (o) {
  25155. _this.scene.addCamera(o);
  25156. });
  25157. this.lights.forEach(function (o) {
  25158. _this.scene.addLight(o);
  25159. });
  25160. this.meshes.forEach(function (o) {
  25161. _this.scene.addMesh(o);
  25162. });
  25163. this.skeletons.forEach(function (o) {
  25164. _this.scene.addSkeleton(o);
  25165. });
  25166. this.particleSystems.forEach(function (o) {
  25167. _this.scene.addParticleSystem(o);
  25168. });
  25169. this.animations.forEach(function (o) {
  25170. _this.scene.addAnimation(o);
  25171. });
  25172. this.multiMaterials.forEach(function (o) {
  25173. _this.scene.addMultiMaterial(o);
  25174. });
  25175. this.materials.forEach(function (o) {
  25176. _this.scene.addMaterial(o);
  25177. });
  25178. this.morphTargetManagers.forEach(function (o) {
  25179. _this.scene.addMorphTargetManager(o);
  25180. });
  25181. this.geometries.forEach(function (o) {
  25182. _this.scene.addGeometry(o);
  25183. });
  25184. this.transformNodes.forEach(function (o) {
  25185. _this.scene.addTransformNode(o);
  25186. });
  25187. this.lensFlareSystems.forEach(function (o) {
  25188. _this.scene.addLensFlareSystem(o);
  25189. });
  25190. this.actionManagers.forEach(function (o) {
  25191. _this.scene.addActionManager(o);
  25192. });
  25193. this.sounds.forEach(function (o) {
  25194. o.play();
  25195. o.autoplay = true;
  25196. _this.scene.mainSoundTrack.AddSound(o);
  25197. });
  25198. };
  25199. /**
  25200. * Removes all the assets in the container from the scene
  25201. */
  25202. AssetContainer.prototype.removeAllFromScene = function () {
  25203. var _this = this;
  25204. this.cameras.forEach(function (o) {
  25205. _this.scene.removeCamera(o);
  25206. });
  25207. this.lights.forEach(function (o) {
  25208. _this.scene.removeLight(o);
  25209. });
  25210. this.meshes.forEach(function (o) {
  25211. _this.scene.removeMesh(o);
  25212. });
  25213. this.skeletons.forEach(function (o) {
  25214. _this.scene.removeSkeleton(o);
  25215. });
  25216. this.particleSystems.forEach(function (o) {
  25217. _this.scene.removeParticleSystem(o);
  25218. });
  25219. this.animations.forEach(function (o) {
  25220. _this.scene.removeAnimation(o);
  25221. });
  25222. this.multiMaterials.forEach(function (o) {
  25223. _this.scene.removeMultiMaterial(o);
  25224. });
  25225. this.materials.forEach(function (o) {
  25226. _this.scene.removeMaterial(o);
  25227. });
  25228. this.morphTargetManagers.forEach(function (o) {
  25229. _this.scene.removeMorphTargetManager(o);
  25230. });
  25231. this.geometries.forEach(function (o) {
  25232. _this.scene.removeGeometry(o);
  25233. });
  25234. this.transformNodes.forEach(function (o) {
  25235. _this.scene.removeTransformNode(o);
  25236. });
  25237. this.lensFlareSystems.forEach(function (o) {
  25238. _this.scene.removeLensFlareSystem(o);
  25239. });
  25240. this.actionManagers.forEach(function (o) {
  25241. _this.scene.removeActionManager(o);
  25242. });
  25243. this.sounds.forEach(function (o) {
  25244. o.stop();
  25245. o.autoplay = false;
  25246. _this.scene.mainSoundTrack.RemoveSound(o);
  25247. });
  25248. };
  25249. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25250. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25251. var asset = sourceAssets_1[_i];
  25252. var move = true;
  25253. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25254. var keepAsset = keepAssets_1[_a];
  25255. if (asset === keepAsset) {
  25256. move = false;
  25257. break;
  25258. }
  25259. }
  25260. if (move) {
  25261. targetAssets.push(asset);
  25262. }
  25263. }
  25264. };
  25265. /**
  25266. * Removes all the assets contained in the scene and adds them to the container.
  25267. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25268. */
  25269. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25270. if (keepAssets === undefined) {
  25271. keepAssets = new KeepAssets();
  25272. }
  25273. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25274. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25275. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25276. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25277. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25278. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25279. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25280. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25281. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25282. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25283. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25284. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25285. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25286. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25287. this.removeAllFromScene();
  25288. };
  25289. return AssetContainer;
  25290. }());
  25291. BABYLON.AssetContainer = AssetContainer;
  25292. })(BABYLON || (BABYLON = {}));
  25293. //# sourceMappingURL=babylon.assetContainer.js.map
  25294. var BABYLON;
  25295. (function (BABYLON) {
  25296. var Buffer = /** @class */ (function () {
  25297. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25298. if (instanced === void 0) { instanced = false; }
  25299. if (engine instanceof BABYLON.Mesh) {
  25300. this._engine = engine.getScene().getEngine();
  25301. }
  25302. else {
  25303. this._engine = engine;
  25304. }
  25305. this._updatable = updatable;
  25306. this._instanced = instanced;
  25307. this._data = data;
  25308. this._strideSize = stride;
  25309. if (!postponeInternalCreation) {
  25310. this.create();
  25311. }
  25312. }
  25313. /**
  25314. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25315. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25316. * @param offset defines offset in the buffer (0 by default)
  25317. * @param size defines the size in floats of attributes (position is 3 for instance)
  25318. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25319. * @param instanced defines if the vertex buffer contains indexed data
  25320. * @returns the new vertex buffer
  25321. */
  25322. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25323. // a lot of these parameters are ignored as they are overriden by the buffer
  25324. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25325. };
  25326. // Properties
  25327. Buffer.prototype.isUpdatable = function () {
  25328. return this._updatable;
  25329. };
  25330. Buffer.prototype.getData = function () {
  25331. return this._data;
  25332. };
  25333. Buffer.prototype.getBuffer = function () {
  25334. return this._buffer;
  25335. };
  25336. Buffer.prototype.getStrideSize = function () {
  25337. return this._strideSize;
  25338. };
  25339. // public getIsInstanced(): boolean {
  25340. // return this._instanced;
  25341. // }
  25342. // public get instanceDivisor(): number {
  25343. // return this._instanceDivisor;
  25344. // }
  25345. // public set instanceDivisor(value: number) {
  25346. // this._instanceDivisor = value;
  25347. // if (value == 0) {
  25348. // this._instanced = false;
  25349. // } else {
  25350. // this._instanced = true;
  25351. // }
  25352. // }
  25353. // Methods
  25354. Buffer.prototype.create = function (data) {
  25355. if (data === void 0) { data = null; }
  25356. if (!data && this._buffer) {
  25357. return; // nothing to do
  25358. }
  25359. data = data || this._data;
  25360. if (!data) {
  25361. return;
  25362. }
  25363. if (!this._buffer) {
  25364. if (this._updatable) {
  25365. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25366. this._data = data;
  25367. }
  25368. else {
  25369. this._buffer = this._engine.createVertexBuffer(data);
  25370. }
  25371. }
  25372. else if (this._updatable) {
  25373. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25374. this._data = data;
  25375. }
  25376. };
  25377. Buffer.prototype._rebuild = function () {
  25378. this._buffer = null;
  25379. this.create(this._data);
  25380. };
  25381. Buffer.prototype.update = function (data) {
  25382. this.create(data);
  25383. };
  25384. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25385. if (!this._buffer) {
  25386. return;
  25387. }
  25388. if (this._updatable) {
  25389. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25390. this._data = null;
  25391. }
  25392. };
  25393. Buffer.prototype.dispose = function () {
  25394. if (!this._buffer) {
  25395. return;
  25396. }
  25397. if (this._engine._releaseBuffer(this._buffer)) {
  25398. this._buffer = null;
  25399. }
  25400. };
  25401. return Buffer;
  25402. }());
  25403. BABYLON.Buffer = Buffer;
  25404. })(BABYLON || (BABYLON = {}));
  25405. //# sourceMappingURL=babylon.buffer.js.map
  25406. var BABYLON;
  25407. (function (BABYLON) {
  25408. var VertexBuffer = /** @class */ (function () {
  25409. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25410. if (data instanceof BABYLON.Buffer) {
  25411. if (!stride) {
  25412. stride = data.getStrideSize();
  25413. }
  25414. this._buffer = data;
  25415. this._ownsBuffer = false;
  25416. }
  25417. else {
  25418. if (!stride) {
  25419. stride = VertexBuffer.DeduceStride(kind);
  25420. }
  25421. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25422. this._ownsBuffer = true;
  25423. }
  25424. this._stride = stride;
  25425. this._instanced = instanced !== undefined ? instanced : false;
  25426. this._instanceDivisor = instanced ? 1 : 0;
  25427. this._offset = offset ? offset : 0;
  25428. this._size = size ? size : stride;
  25429. this._kind = kind;
  25430. }
  25431. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25432. /**
  25433. * Gets or sets the instance divisor when in instanced mode
  25434. */
  25435. get: function () {
  25436. return this._instanceDivisor;
  25437. },
  25438. set: function (value) {
  25439. this._instanceDivisor = value;
  25440. if (value == 0) {
  25441. this._instanced = false;
  25442. }
  25443. else {
  25444. this._instanced = true;
  25445. }
  25446. },
  25447. enumerable: true,
  25448. configurable: true
  25449. });
  25450. VertexBuffer.prototype._rebuild = function () {
  25451. if (!this._buffer) {
  25452. return;
  25453. }
  25454. this._buffer._rebuild();
  25455. };
  25456. /**
  25457. * Returns the kind of the VertexBuffer (string).
  25458. */
  25459. VertexBuffer.prototype.getKind = function () {
  25460. return this._kind;
  25461. };
  25462. // Properties
  25463. /**
  25464. * Boolean : is the VertexBuffer updatable ?
  25465. */
  25466. VertexBuffer.prototype.isUpdatable = function () {
  25467. return this._buffer.isUpdatable();
  25468. };
  25469. /**
  25470. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25471. */
  25472. VertexBuffer.prototype.getData = function () {
  25473. return this._buffer.getData();
  25474. };
  25475. /**
  25476. * Returns the WebGLBuffer associated to the VertexBuffer.
  25477. */
  25478. VertexBuffer.prototype.getBuffer = function () {
  25479. return this._buffer.getBuffer();
  25480. };
  25481. /**
  25482. * Returns the stride of the VertexBuffer (integer).
  25483. */
  25484. VertexBuffer.prototype.getStrideSize = function () {
  25485. return this._stride;
  25486. };
  25487. /**
  25488. * Returns the offset (integer).
  25489. */
  25490. VertexBuffer.prototype.getOffset = function () {
  25491. return this._offset;
  25492. };
  25493. /**
  25494. * Returns the VertexBuffer total size (integer).
  25495. */
  25496. VertexBuffer.prototype.getSize = function () {
  25497. return this._size;
  25498. };
  25499. /**
  25500. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25501. */
  25502. VertexBuffer.prototype.getIsInstanced = function () {
  25503. return this._instanced;
  25504. };
  25505. /**
  25506. * Returns the instancing divisor, zero for non-instanced (integer).
  25507. */
  25508. VertexBuffer.prototype.getInstanceDivisor = function () {
  25509. return this._instanceDivisor;
  25510. };
  25511. // Methods
  25512. /**
  25513. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25514. * Returns the created WebGLBuffer.
  25515. */
  25516. VertexBuffer.prototype.create = function (data) {
  25517. return this._buffer.create(data);
  25518. };
  25519. /**
  25520. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25521. * This function will create a new buffer if the current one is not updatable
  25522. * Returns the updated WebGLBuffer.
  25523. */
  25524. VertexBuffer.prototype.update = function (data) {
  25525. return this._buffer.update(data);
  25526. };
  25527. /**
  25528. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25529. * Returns the directly updated WebGLBuffer.
  25530. */
  25531. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25532. return this._buffer.updateDirectly(data, offset);
  25533. };
  25534. /**
  25535. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25536. */
  25537. VertexBuffer.prototype.dispose = function () {
  25538. if (this._ownsBuffer) {
  25539. this._buffer.dispose();
  25540. }
  25541. };
  25542. Object.defineProperty(VertexBuffer, "PositionKind", {
  25543. get: function () {
  25544. return VertexBuffer._PositionKind;
  25545. },
  25546. enumerable: true,
  25547. configurable: true
  25548. });
  25549. Object.defineProperty(VertexBuffer, "NormalKind", {
  25550. get: function () {
  25551. return VertexBuffer._NormalKind;
  25552. },
  25553. enumerable: true,
  25554. configurable: true
  25555. });
  25556. Object.defineProperty(VertexBuffer, "TangentKind", {
  25557. get: function () {
  25558. return VertexBuffer._TangentKind;
  25559. },
  25560. enumerable: true,
  25561. configurable: true
  25562. });
  25563. Object.defineProperty(VertexBuffer, "UVKind", {
  25564. get: function () {
  25565. return VertexBuffer._UVKind;
  25566. },
  25567. enumerable: true,
  25568. configurable: true
  25569. });
  25570. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25571. get: function () {
  25572. return VertexBuffer._UV2Kind;
  25573. },
  25574. enumerable: true,
  25575. configurable: true
  25576. });
  25577. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25578. get: function () {
  25579. return VertexBuffer._UV3Kind;
  25580. },
  25581. enumerable: true,
  25582. configurable: true
  25583. });
  25584. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25585. get: function () {
  25586. return VertexBuffer._UV4Kind;
  25587. },
  25588. enumerable: true,
  25589. configurable: true
  25590. });
  25591. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25592. get: function () {
  25593. return VertexBuffer._UV5Kind;
  25594. },
  25595. enumerable: true,
  25596. configurable: true
  25597. });
  25598. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25599. get: function () {
  25600. return VertexBuffer._UV6Kind;
  25601. },
  25602. enumerable: true,
  25603. configurable: true
  25604. });
  25605. Object.defineProperty(VertexBuffer, "ColorKind", {
  25606. get: function () {
  25607. return VertexBuffer._ColorKind;
  25608. },
  25609. enumerable: true,
  25610. configurable: true
  25611. });
  25612. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25613. get: function () {
  25614. return VertexBuffer._MatricesIndicesKind;
  25615. },
  25616. enumerable: true,
  25617. configurable: true
  25618. });
  25619. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25620. get: function () {
  25621. return VertexBuffer._MatricesWeightsKind;
  25622. },
  25623. enumerable: true,
  25624. configurable: true
  25625. });
  25626. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25627. get: function () {
  25628. return VertexBuffer._MatricesIndicesExtraKind;
  25629. },
  25630. enumerable: true,
  25631. configurable: true
  25632. });
  25633. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25634. get: function () {
  25635. return VertexBuffer._MatricesWeightsExtraKind;
  25636. },
  25637. enumerable: true,
  25638. configurable: true
  25639. });
  25640. /**
  25641. * Deduces the stride given a kind.
  25642. * @param kind The kind string to deduce
  25643. * @returns The deduced stride
  25644. */
  25645. VertexBuffer.DeduceStride = function (kind) {
  25646. switch (kind) {
  25647. case VertexBuffer.UVKind:
  25648. case VertexBuffer.UV2Kind:
  25649. case VertexBuffer.UV3Kind:
  25650. case VertexBuffer.UV4Kind:
  25651. case VertexBuffer.UV5Kind:
  25652. case VertexBuffer.UV6Kind:
  25653. return 2;
  25654. case VertexBuffer.NormalKind:
  25655. case VertexBuffer.PositionKind:
  25656. return 3;
  25657. case VertexBuffer.ColorKind:
  25658. case VertexBuffer.MatricesIndicesKind:
  25659. case VertexBuffer.MatricesIndicesExtraKind:
  25660. case VertexBuffer.MatricesWeightsKind:
  25661. case VertexBuffer.MatricesWeightsExtraKind:
  25662. case VertexBuffer.TangentKind:
  25663. return 4;
  25664. default:
  25665. throw new Error("Invalid kind '" + kind + "'");
  25666. }
  25667. };
  25668. // Enums
  25669. VertexBuffer._PositionKind = "position";
  25670. VertexBuffer._NormalKind = "normal";
  25671. VertexBuffer._TangentKind = "tangent";
  25672. VertexBuffer._UVKind = "uv";
  25673. VertexBuffer._UV2Kind = "uv2";
  25674. VertexBuffer._UV3Kind = "uv3";
  25675. VertexBuffer._UV4Kind = "uv4";
  25676. VertexBuffer._UV5Kind = "uv5";
  25677. VertexBuffer._UV6Kind = "uv6";
  25678. VertexBuffer._ColorKind = "color";
  25679. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25680. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25681. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25682. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25683. return VertexBuffer;
  25684. }());
  25685. BABYLON.VertexBuffer = VertexBuffer;
  25686. })(BABYLON || (BABYLON = {}));
  25687. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25688. var BABYLON;
  25689. (function (BABYLON) {
  25690. /**
  25691. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25692. */
  25693. var DummyInternalTextureTracker = /** @class */ (function () {
  25694. function DummyInternalTextureTracker() {
  25695. /**
  25696. * Gets or set the previous tracker in the list
  25697. */
  25698. this.previous = null;
  25699. /**
  25700. * Gets or set the next tracker in the list
  25701. */
  25702. this.next = null;
  25703. }
  25704. return DummyInternalTextureTracker;
  25705. }());
  25706. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25707. })(BABYLON || (BABYLON = {}));
  25708. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  25709. var BABYLON;
  25710. (function (BABYLON) {
  25711. /**
  25712. * Class used to store data associated with WebGL texture data for the engine
  25713. * This class should not be used directly
  25714. */
  25715. var InternalTexture = /** @class */ (function () {
  25716. /**
  25717. * Creates a new InternalTexture
  25718. * @param engine defines the engine to use
  25719. * @param dataSource defines the type of data that will be used
  25720. */
  25721. function InternalTexture(engine, dataSource) {
  25722. /**
  25723. * Observable called when the texture is loaded
  25724. */
  25725. this.onLoadedObservable = new BABYLON.Observable();
  25726. /**
  25727. * Gets or set the previous tracker in the list
  25728. */
  25729. this.previous = null;
  25730. /**
  25731. * Gets or set the next tracker in the list
  25732. */
  25733. this.next = null;
  25734. // Private
  25735. /** @ignore */
  25736. this._initialSlot = -1;
  25737. /** @ignore */
  25738. this._designatedSlot = -1;
  25739. /** @ignore */
  25740. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  25741. /** @ignore */
  25742. this._references = 1;
  25743. this._engine = engine;
  25744. this._dataSource = dataSource;
  25745. this._webGLTexture = engine._createTexture();
  25746. }
  25747. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  25748. /**
  25749. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  25750. */
  25751. get: function () {
  25752. return this._dataSource;
  25753. },
  25754. enumerable: true,
  25755. configurable: true
  25756. });
  25757. /**
  25758. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  25759. */
  25760. InternalTexture.prototype.incrementReferences = function () {
  25761. this._references++;
  25762. };
  25763. /**
  25764. * Change the size of the texture (not the size of the content)
  25765. * @param width defines the new width
  25766. * @param height defines the new height
  25767. * @param depth defines the new depth (1 by default)
  25768. */
  25769. InternalTexture.prototype.updateSize = function (width, height, depth) {
  25770. if (depth === void 0) { depth = 1; }
  25771. this.width = width;
  25772. this.height = height;
  25773. this.depth = depth;
  25774. this.baseWidth = width;
  25775. this.baseHeight = height;
  25776. this.baseDepth = depth;
  25777. this._size = width * height * depth;
  25778. };
  25779. /** @ignore */
  25780. InternalTexture.prototype._rebuild = function () {
  25781. var _this = this;
  25782. var proxy;
  25783. this.isReady = false;
  25784. this._cachedCoordinatesMode = null;
  25785. this._cachedWrapU = null;
  25786. this._cachedWrapV = null;
  25787. this._cachedAnisotropicFilteringLevel = null;
  25788. switch (this._dataSource) {
  25789. case InternalTexture.DATASOURCE_TEMP:
  25790. return;
  25791. case InternalTexture.DATASOURCE_URL:
  25792. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  25793. _this.isReady = true;
  25794. }, null, this._buffer, undefined, this.format);
  25795. proxy._swapAndDie(this);
  25796. return;
  25797. case InternalTexture.DATASOURCE_RAW:
  25798. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25799. proxy._swapAndDie(this);
  25800. this.isReady = true;
  25801. return;
  25802. case InternalTexture.DATASOURCE_RAW3D:
  25803. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25804. proxy._swapAndDie(this);
  25805. this.isReady = true;
  25806. return;
  25807. case InternalTexture.DATASOURCE_DYNAMIC:
  25808. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  25809. proxy._swapAndDie(this);
  25810. // The engine will make sure to update content so no need to flag it as isReady = true
  25811. return;
  25812. case InternalTexture.DATASOURCE_RENDERTARGET:
  25813. var options = new BABYLON.RenderTargetCreationOptions();
  25814. options.generateDepthBuffer = this._generateDepthBuffer;
  25815. options.generateMipMaps = this.generateMipMaps;
  25816. options.generateStencilBuffer = this._generateStencilBuffer;
  25817. options.samplingMode = this.samplingMode;
  25818. options.type = this.type;
  25819. if (this.isCube) {
  25820. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  25821. }
  25822. else {
  25823. var size = {
  25824. width: this.width,
  25825. height: this.height
  25826. };
  25827. proxy = this._engine.createRenderTargetTexture(size, options);
  25828. }
  25829. proxy._swapAndDie(this);
  25830. this.isReady = true;
  25831. return;
  25832. case InternalTexture.DATASOURCE_CUBE:
  25833. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  25834. _this.isReady = true;
  25835. }, null, this.format, this._extension);
  25836. proxy._swapAndDie(this);
  25837. return;
  25838. case InternalTexture.DATASOURCE_CUBERAW:
  25839. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25840. proxy._swapAndDie(this);
  25841. this.isReady = true;
  25842. return;
  25843. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  25844. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  25845. if (proxy) {
  25846. proxy._swapAndDie(_this);
  25847. }
  25848. _this.isReady = true;
  25849. }, null, this.format, this._extension);
  25850. return;
  25851. }
  25852. };
  25853. InternalTexture.prototype._swapAndDie = function (target) {
  25854. target._webGLTexture = this._webGLTexture;
  25855. if (this._framebuffer) {
  25856. target._framebuffer = this._framebuffer;
  25857. }
  25858. if (this._depthStencilBuffer) {
  25859. target._depthStencilBuffer = this._depthStencilBuffer;
  25860. }
  25861. if (this._lodTextureHigh) {
  25862. if (target._lodTextureHigh) {
  25863. target._lodTextureHigh.dispose();
  25864. }
  25865. target._lodTextureHigh = this._lodTextureHigh;
  25866. }
  25867. if (this._lodTextureMid) {
  25868. if (target._lodTextureMid) {
  25869. target._lodTextureMid.dispose();
  25870. }
  25871. target._lodTextureMid = this._lodTextureMid;
  25872. }
  25873. if (this._lodTextureLow) {
  25874. if (target._lodTextureLow) {
  25875. target._lodTextureLow.dispose();
  25876. }
  25877. target._lodTextureLow = this._lodTextureLow;
  25878. }
  25879. var cache = this._engine.getLoadedTexturesCache();
  25880. var index = cache.indexOf(this);
  25881. if (index !== -1) {
  25882. cache.splice(index, 1);
  25883. }
  25884. };
  25885. /**
  25886. * Dispose the current allocated resources
  25887. */
  25888. InternalTexture.prototype.dispose = function () {
  25889. if (!this._webGLTexture) {
  25890. return;
  25891. }
  25892. this._references--;
  25893. if (this._references === 0) {
  25894. this._engine._releaseTexture(this);
  25895. this._webGLTexture = null;
  25896. this.previous = null;
  25897. this.next = null;
  25898. }
  25899. };
  25900. /**
  25901. * The source of the texture data is unknown
  25902. */
  25903. InternalTexture.DATASOURCE_UNKNOWN = 0;
  25904. /**
  25905. * Texture data comes from an URL
  25906. */
  25907. InternalTexture.DATASOURCE_URL = 1;
  25908. /**
  25909. * Texture data is only used for temporary storage
  25910. */
  25911. InternalTexture.DATASOURCE_TEMP = 2;
  25912. /**
  25913. * Texture data comes from raw data (ArrayBuffer)
  25914. */
  25915. InternalTexture.DATASOURCE_RAW = 3;
  25916. /**
  25917. * Texture content is dynamic (video or dynamic texture)
  25918. */
  25919. InternalTexture.DATASOURCE_DYNAMIC = 4;
  25920. /**
  25921. * Texture content is generated by rendering to it
  25922. */
  25923. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  25924. /**
  25925. * Texture content is part of a multi render target process
  25926. */
  25927. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  25928. /**
  25929. * Texture data comes from a cube data file
  25930. */
  25931. InternalTexture.DATASOURCE_CUBE = 7;
  25932. /**
  25933. * Texture data comes from a raw cube data
  25934. */
  25935. InternalTexture.DATASOURCE_CUBERAW = 8;
  25936. /**
  25937. * Texture data come from a prefiltered cube data file
  25938. */
  25939. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  25940. /**
  25941. * Texture content is raw 3D data
  25942. */
  25943. InternalTexture.DATASOURCE_RAW3D = 10;
  25944. return InternalTexture;
  25945. }());
  25946. BABYLON.InternalTexture = InternalTexture;
  25947. })(BABYLON || (BABYLON = {}));
  25948. //# sourceMappingURL=babylon.internalTexture.js.map
  25949. var BABYLON;
  25950. (function (BABYLON) {
  25951. var BaseTexture = /** @class */ (function () {
  25952. function BaseTexture(scene) {
  25953. this._hasAlpha = false;
  25954. this.getAlphaFromRGB = false;
  25955. this.level = 1;
  25956. this.coordinatesIndex = 0;
  25957. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  25958. /**
  25959. * | Value | Type | Description |
  25960. * | ----- | ------------------ | ----------- |
  25961. * | 0 | CLAMP_ADDRESSMODE | |
  25962. * | 1 | WRAP_ADDRESSMODE | |
  25963. * | 2 | MIRROR_ADDRESSMODE | |
  25964. */
  25965. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25966. /**
  25967. * | Value | Type | Description |
  25968. * | ----- | ------------------ | ----------- |
  25969. * | 0 | CLAMP_ADDRESSMODE | |
  25970. * | 1 | WRAP_ADDRESSMODE | |
  25971. * | 2 | MIRROR_ADDRESSMODE | |
  25972. */
  25973. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25974. /**
  25975. * | Value | Type | Description |
  25976. * | ----- | ------------------ | ----------- |
  25977. * | 0 | CLAMP_ADDRESSMODE | |
  25978. * | 1 | WRAP_ADDRESSMODE | |
  25979. * | 2 | MIRROR_ADDRESSMODE | |
  25980. */
  25981. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  25982. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  25983. this.isCube = false;
  25984. this.is3D = false;
  25985. this.gammaSpace = true;
  25986. this.invertZ = false;
  25987. this.lodLevelInAlpha = false;
  25988. this.lodGenerationOffset = 0.0;
  25989. this.lodGenerationScale = 0.8;
  25990. this.isRenderTarget = false;
  25991. this.animations = new Array();
  25992. /**
  25993. * An event triggered when the texture is disposed.
  25994. * @type {BABYLON.Observable}
  25995. */
  25996. this.onDisposeObservable = new BABYLON.Observable();
  25997. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25998. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25999. if (this._scene) {
  26000. this._scene.textures.push(this);
  26001. }
  26002. this._uid = null;
  26003. }
  26004. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26005. get: function () {
  26006. return this._hasAlpha;
  26007. },
  26008. set: function (value) {
  26009. if (this._hasAlpha === value) {
  26010. return;
  26011. }
  26012. this._hasAlpha = value;
  26013. if (this._scene) {
  26014. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26015. }
  26016. },
  26017. enumerable: true,
  26018. configurable: true
  26019. });
  26020. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26021. get: function () {
  26022. return this._coordinatesMode;
  26023. },
  26024. /**
  26025. * How a texture is mapped.
  26026. *
  26027. * | Value | Type | Description |
  26028. * | ----- | ----------------------------------- | ----------- |
  26029. * | 0 | EXPLICIT_MODE | |
  26030. * | 1 | SPHERICAL_MODE | |
  26031. * | 2 | PLANAR_MODE | |
  26032. * | 3 | CUBIC_MODE | |
  26033. * | 4 | PROJECTION_MODE | |
  26034. * | 5 | SKYBOX_MODE | |
  26035. * | 6 | INVCUBIC_MODE | |
  26036. * | 7 | EQUIRECTANGULAR_MODE | |
  26037. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26038. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26039. */
  26040. set: function (value) {
  26041. if (this._coordinatesMode === value) {
  26042. return;
  26043. }
  26044. this._coordinatesMode = value;
  26045. if (this._scene) {
  26046. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26047. }
  26048. },
  26049. enumerable: true,
  26050. configurable: true
  26051. });
  26052. Object.defineProperty(BaseTexture.prototype, "uid", {
  26053. get: function () {
  26054. if (!this._uid) {
  26055. this._uid = BABYLON.Tools.RandomId();
  26056. }
  26057. return this._uid;
  26058. },
  26059. enumerable: true,
  26060. configurable: true
  26061. });
  26062. BaseTexture.prototype.toString = function () {
  26063. return this.name;
  26064. };
  26065. BaseTexture.prototype.getClassName = function () {
  26066. return "BaseTexture";
  26067. };
  26068. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26069. set: function (callback) {
  26070. if (this._onDisposeObserver) {
  26071. this.onDisposeObservable.remove(this._onDisposeObserver);
  26072. }
  26073. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26074. },
  26075. enumerable: true,
  26076. configurable: true
  26077. });
  26078. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26079. get: function () {
  26080. return true;
  26081. },
  26082. enumerable: true,
  26083. configurable: true
  26084. });
  26085. BaseTexture.prototype.getScene = function () {
  26086. return this._scene;
  26087. };
  26088. BaseTexture.prototype.getTextureMatrix = function () {
  26089. return BABYLON.Matrix.IdentityReadOnly;
  26090. };
  26091. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26092. return BABYLON.Matrix.IdentityReadOnly;
  26093. };
  26094. BaseTexture.prototype.getInternalTexture = function () {
  26095. return this._texture;
  26096. };
  26097. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26098. return !this.isBlocking || this.isReady();
  26099. };
  26100. BaseTexture.prototype.isReady = function () {
  26101. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26102. this.delayLoad();
  26103. return false;
  26104. }
  26105. if (this._texture) {
  26106. return this._texture.isReady;
  26107. }
  26108. return false;
  26109. };
  26110. BaseTexture.prototype.getSize = function () {
  26111. if (this._texture && this._texture.width) {
  26112. return new BABYLON.Size(this._texture.width, this._texture.height);
  26113. }
  26114. if (this._texture && this._texture._size) {
  26115. return new BABYLON.Size(this._texture._size, this._texture._size);
  26116. }
  26117. return BABYLON.Size.Zero();
  26118. };
  26119. BaseTexture.prototype.getBaseSize = function () {
  26120. if (!this.isReady() || !this._texture)
  26121. return BABYLON.Size.Zero();
  26122. if (this._texture._size) {
  26123. return new BABYLON.Size(this._texture._size, this._texture._size);
  26124. }
  26125. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26126. };
  26127. BaseTexture.prototype.scale = function (ratio) {
  26128. };
  26129. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26130. get: function () {
  26131. return false;
  26132. },
  26133. enumerable: true,
  26134. configurable: true
  26135. });
  26136. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26137. if (!this._scene) {
  26138. return null;
  26139. }
  26140. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26141. for (var index = 0; index < texturesCache.length; index++) {
  26142. var texturesCacheEntry = texturesCache[index];
  26143. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26144. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26145. texturesCacheEntry.incrementReferences();
  26146. return texturesCacheEntry;
  26147. }
  26148. }
  26149. }
  26150. return null;
  26151. };
  26152. BaseTexture.prototype._rebuild = function () {
  26153. };
  26154. BaseTexture.prototype.delayLoad = function () {
  26155. };
  26156. BaseTexture.prototype.clone = function () {
  26157. return null;
  26158. };
  26159. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26160. get: function () {
  26161. if (!this._texture) {
  26162. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26163. }
  26164. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26165. },
  26166. enumerable: true,
  26167. configurable: true
  26168. });
  26169. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26170. get: function () {
  26171. if (!this._texture) {
  26172. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26173. }
  26174. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26175. },
  26176. enumerable: true,
  26177. configurable: true
  26178. });
  26179. BaseTexture.prototype.readPixels = function (faceIndex) {
  26180. if (faceIndex === void 0) { faceIndex = 0; }
  26181. if (!this._texture) {
  26182. return null;
  26183. }
  26184. var size = this.getSize();
  26185. var scene = this.getScene();
  26186. if (!scene) {
  26187. return null;
  26188. }
  26189. var engine = scene.getEngine();
  26190. if (this._texture.isCube) {
  26191. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26192. }
  26193. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26194. };
  26195. BaseTexture.prototype.releaseInternalTexture = function () {
  26196. if (this._texture) {
  26197. this._texture.dispose();
  26198. this._texture = null;
  26199. }
  26200. };
  26201. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26202. get: function () {
  26203. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26204. return null;
  26205. }
  26206. if (!this._texture._sphericalPolynomial) {
  26207. this._texture._sphericalPolynomial =
  26208. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26209. }
  26210. return this._texture._sphericalPolynomial;
  26211. },
  26212. set: function (value) {
  26213. if (this._texture) {
  26214. this._texture._sphericalPolynomial = value;
  26215. }
  26216. },
  26217. enumerable: true,
  26218. configurable: true
  26219. });
  26220. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26221. get: function () {
  26222. if (this._texture) {
  26223. return this._texture._lodTextureHigh;
  26224. }
  26225. return null;
  26226. },
  26227. enumerable: true,
  26228. configurable: true
  26229. });
  26230. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26231. get: function () {
  26232. if (this._texture) {
  26233. return this._texture._lodTextureMid;
  26234. }
  26235. return null;
  26236. },
  26237. enumerable: true,
  26238. configurable: true
  26239. });
  26240. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26241. get: function () {
  26242. if (this._texture) {
  26243. return this._texture._lodTextureLow;
  26244. }
  26245. return null;
  26246. },
  26247. enumerable: true,
  26248. configurable: true
  26249. });
  26250. BaseTexture.prototype.dispose = function () {
  26251. if (!this._scene) {
  26252. return;
  26253. }
  26254. // Animations
  26255. this._scene.stopAnimation(this);
  26256. // Remove from scene
  26257. this._scene._removePendingData(this);
  26258. var index = this._scene.textures.indexOf(this);
  26259. if (index >= 0) {
  26260. this._scene.textures.splice(index, 1);
  26261. }
  26262. if (this._texture === undefined) {
  26263. return;
  26264. }
  26265. // Release
  26266. this.releaseInternalTexture();
  26267. // Callback
  26268. this.onDisposeObservable.notifyObservers(this);
  26269. this.onDisposeObservable.clear();
  26270. };
  26271. BaseTexture.prototype.serialize = function () {
  26272. if (!this.name) {
  26273. return null;
  26274. }
  26275. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26276. // Animations
  26277. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26278. return serializationObject;
  26279. };
  26280. BaseTexture.WhenAllReady = function (textures, callback) {
  26281. var numRemaining = textures.length;
  26282. if (numRemaining === 0) {
  26283. callback();
  26284. return;
  26285. }
  26286. var _loop_1 = function () {
  26287. texture = textures[i];
  26288. if (texture.isReady()) {
  26289. if (--numRemaining === 0) {
  26290. callback();
  26291. }
  26292. }
  26293. else {
  26294. onLoadObservable = texture.onLoadObservable;
  26295. var onLoadCallback_1 = function () {
  26296. onLoadObservable.removeCallback(onLoadCallback_1);
  26297. if (--numRemaining === 0) {
  26298. callback();
  26299. }
  26300. };
  26301. onLoadObservable.add(onLoadCallback_1);
  26302. }
  26303. };
  26304. var texture, onLoadObservable;
  26305. for (var i = 0; i < textures.length; i++) {
  26306. _loop_1();
  26307. }
  26308. };
  26309. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26310. __decorate([
  26311. BABYLON.serialize()
  26312. ], BaseTexture.prototype, "name", void 0);
  26313. __decorate([
  26314. BABYLON.serialize("hasAlpha")
  26315. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26316. __decorate([
  26317. BABYLON.serialize()
  26318. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26319. __decorate([
  26320. BABYLON.serialize()
  26321. ], BaseTexture.prototype, "level", void 0);
  26322. __decorate([
  26323. BABYLON.serialize()
  26324. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26325. __decorate([
  26326. BABYLON.serialize("coordinatesMode")
  26327. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26328. __decorate([
  26329. BABYLON.serialize()
  26330. ], BaseTexture.prototype, "wrapU", void 0);
  26331. __decorate([
  26332. BABYLON.serialize()
  26333. ], BaseTexture.prototype, "wrapV", void 0);
  26334. __decorate([
  26335. BABYLON.serialize()
  26336. ], BaseTexture.prototype, "wrapR", void 0);
  26337. __decorate([
  26338. BABYLON.serialize()
  26339. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26340. __decorate([
  26341. BABYLON.serialize()
  26342. ], BaseTexture.prototype, "isCube", void 0);
  26343. __decorate([
  26344. BABYLON.serialize()
  26345. ], BaseTexture.prototype, "is3D", void 0);
  26346. __decorate([
  26347. BABYLON.serialize()
  26348. ], BaseTexture.prototype, "gammaSpace", void 0);
  26349. __decorate([
  26350. BABYLON.serialize()
  26351. ], BaseTexture.prototype, "invertZ", void 0);
  26352. __decorate([
  26353. BABYLON.serialize()
  26354. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26355. __decorate([
  26356. BABYLON.serialize()
  26357. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26358. __decorate([
  26359. BABYLON.serialize()
  26360. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26361. __decorate([
  26362. BABYLON.serialize()
  26363. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26364. return BaseTexture;
  26365. }());
  26366. BABYLON.BaseTexture = BaseTexture;
  26367. })(BABYLON || (BABYLON = {}));
  26368. //# sourceMappingURL=babylon.baseTexture.js.map
  26369. var BABYLON;
  26370. (function (BABYLON) {
  26371. var Texture = /** @class */ (function (_super) {
  26372. __extends(Texture, _super);
  26373. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26374. if (noMipmap === void 0) { noMipmap = false; }
  26375. if (invertY === void 0) { invertY = true; }
  26376. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26377. if (onLoad === void 0) { onLoad = null; }
  26378. if (onError === void 0) { onError = null; }
  26379. if (buffer === void 0) { buffer = null; }
  26380. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26381. var _this = _super.call(this, scene) || this;
  26382. _this.uOffset = 0;
  26383. _this.vOffset = 0;
  26384. _this.uScale = 1.0;
  26385. _this.vScale = 1.0;
  26386. _this.uAng = 0;
  26387. _this.vAng = 0;
  26388. _this.wAng = 0;
  26389. _this._isBlocking = true;
  26390. _this.name = url || "";
  26391. _this.url = url;
  26392. _this._noMipmap = noMipmap;
  26393. _this._invertY = invertY;
  26394. _this._samplingMode = samplingMode;
  26395. _this._buffer = buffer;
  26396. _this._deleteBuffer = deleteBuffer;
  26397. if (format) {
  26398. _this._format = format;
  26399. }
  26400. scene = _this.getScene();
  26401. if (!scene) {
  26402. return _this;
  26403. }
  26404. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26405. var load = function () {
  26406. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26407. _this.onLoadObservable.notifyObservers(_this);
  26408. }
  26409. if (onLoad) {
  26410. onLoad();
  26411. }
  26412. if (!_this.isBlocking && scene) {
  26413. scene.resetCachedMaterial();
  26414. }
  26415. };
  26416. if (!_this.url) {
  26417. _this._delayedOnLoad = load;
  26418. _this._delayedOnError = onError;
  26419. return _this;
  26420. }
  26421. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26422. if (!_this._texture) {
  26423. if (!scene.useDelayedTextureLoading) {
  26424. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26425. if (deleteBuffer) {
  26426. delete _this._buffer;
  26427. }
  26428. }
  26429. else {
  26430. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26431. _this._delayedOnLoad = load;
  26432. _this._delayedOnError = onError;
  26433. }
  26434. }
  26435. else {
  26436. if (_this._texture.isReady) {
  26437. BABYLON.Tools.SetImmediate(function () { return load(); });
  26438. }
  26439. else {
  26440. _this._texture.onLoadedObservable.add(load);
  26441. }
  26442. }
  26443. return _this;
  26444. }
  26445. Object.defineProperty(Texture.prototype, "noMipmap", {
  26446. get: function () {
  26447. return this._noMipmap;
  26448. },
  26449. enumerable: true,
  26450. configurable: true
  26451. });
  26452. Object.defineProperty(Texture.prototype, "isBlocking", {
  26453. get: function () {
  26454. return this._isBlocking;
  26455. },
  26456. set: function (value) {
  26457. this._isBlocking = value;
  26458. },
  26459. enumerable: true,
  26460. configurable: true
  26461. });
  26462. Object.defineProperty(Texture.prototype, "samplingMode", {
  26463. get: function () {
  26464. return this._samplingMode;
  26465. },
  26466. enumerable: true,
  26467. configurable: true
  26468. });
  26469. Texture.prototype.updateURL = function (url) {
  26470. this.url = url;
  26471. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26472. this.delayLoad();
  26473. };
  26474. Texture.prototype.delayLoad = function () {
  26475. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26476. return;
  26477. }
  26478. var scene = this.getScene();
  26479. if (!scene) {
  26480. return;
  26481. }
  26482. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26483. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26484. if (!this._texture) {
  26485. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26486. if (this._deleteBuffer) {
  26487. delete this._buffer;
  26488. }
  26489. }
  26490. else {
  26491. if (this._delayedOnLoad) {
  26492. if (this._texture.isReady) {
  26493. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26494. }
  26495. else {
  26496. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26497. }
  26498. }
  26499. }
  26500. this._delayedOnLoad = null;
  26501. this._delayedOnError = null;
  26502. };
  26503. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26504. if (!this._texture) {
  26505. return;
  26506. }
  26507. var scene = this.getScene();
  26508. if (!scene) {
  26509. return;
  26510. }
  26511. this._samplingMode = samplingMode;
  26512. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26513. };
  26514. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26515. x *= this.uScale;
  26516. y *= this.vScale;
  26517. x -= 0.5 * this.uScale;
  26518. y -= 0.5 * this.vScale;
  26519. z -= 0.5;
  26520. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26521. t.x += 0.5 * this.uScale + this.uOffset;
  26522. t.y += 0.5 * this.vScale + this.vOffset;
  26523. t.z += 0.5;
  26524. };
  26525. Texture.prototype.getTextureMatrix = function () {
  26526. var _this = this;
  26527. if (this.uOffset === this._cachedUOffset &&
  26528. this.vOffset === this._cachedVOffset &&
  26529. this.uScale === this._cachedUScale &&
  26530. this.vScale === this._cachedVScale &&
  26531. this.uAng === this._cachedUAng &&
  26532. this.vAng === this._cachedVAng &&
  26533. this.wAng === this._cachedWAng) {
  26534. return this._cachedTextureMatrix;
  26535. }
  26536. this._cachedUOffset = this.uOffset;
  26537. this._cachedVOffset = this.vOffset;
  26538. this._cachedUScale = this.uScale;
  26539. this._cachedVScale = this.vScale;
  26540. this._cachedUAng = this.uAng;
  26541. this._cachedVAng = this.vAng;
  26542. this._cachedWAng = this.wAng;
  26543. if (!this._cachedTextureMatrix) {
  26544. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26545. this._rowGenerationMatrix = new BABYLON.Matrix();
  26546. this._t0 = BABYLON.Vector3.Zero();
  26547. this._t1 = BABYLON.Vector3.Zero();
  26548. this._t2 = BABYLON.Vector3.Zero();
  26549. }
  26550. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26551. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26552. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26553. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26554. this._t1.subtractInPlace(this._t0);
  26555. this._t2.subtractInPlace(this._t0);
  26556. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26557. this._cachedTextureMatrix.m[0] = this._t1.x;
  26558. this._cachedTextureMatrix.m[1] = this._t1.y;
  26559. this._cachedTextureMatrix.m[2] = this._t1.z;
  26560. this._cachedTextureMatrix.m[4] = this._t2.x;
  26561. this._cachedTextureMatrix.m[5] = this._t2.y;
  26562. this._cachedTextureMatrix.m[6] = this._t2.z;
  26563. this._cachedTextureMatrix.m[8] = this._t0.x;
  26564. this._cachedTextureMatrix.m[9] = this._t0.y;
  26565. this._cachedTextureMatrix.m[10] = this._t0.z;
  26566. var scene = this.getScene();
  26567. if (!scene) {
  26568. return this._cachedTextureMatrix;
  26569. }
  26570. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26571. return mat.hasTexture(_this);
  26572. });
  26573. return this._cachedTextureMatrix;
  26574. };
  26575. Texture.prototype.getReflectionTextureMatrix = function () {
  26576. var _this = this;
  26577. var scene = this.getScene();
  26578. if (!scene) {
  26579. return this._cachedTextureMatrix;
  26580. }
  26581. if (this.uOffset === this._cachedUOffset &&
  26582. this.vOffset === this._cachedVOffset &&
  26583. this.uScale === this._cachedUScale &&
  26584. this.vScale === this._cachedVScale &&
  26585. this.coordinatesMode === this._cachedCoordinatesMode) {
  26586. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26587. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26588. return this._cachedTextureMatrix;
  26589. }
  26590. }
  26591. else {
  26592. return this._cachedTextureMatrix;
  26593. }
  26594. }
  26595. if (!this._cachedTextureMatrix) {
  26596. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26597. }
  26598. if (!this._projectionModeMatrix) {
  26599. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26600. }
  26601. this._cachedUOffset = this.uOffset;
  26602. this._cachedVOffset = this.vOffset;
  26603. this._cachedUScale = this.uScale;
  26604. this._cachedVScale = this.vScale;
  26605. this._cachedCoordinatesMode = this.coordinatesMode;
  26606. switch (this.coordinatesMode) {
  26607. case Texture.PLANAR_MODE:
  26608. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26609. this._cachedTextureMatrix[0] = this.uScale;
  26610. this._cachedTextureMatrix[5] = this.vScale;
  26611. this._cachedTextureMatrix[12] = this.uOffset;
  26612. this._cachedTextureMatrix[13] = this.vOffset;
  26613. break;
  26614. case Texture.PROJECTION_MODE:
  26615. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26616. this._projectionModeMatrix.m[0] = 0.5;
  26617. this._projectionModeMatrix.m[5] = -0.5;
  26618. this._projectionModeMatrix.m[10] = 0.0;
  26619. this._projectionModeMatrix.m[12] = 0.5;
  26620. this._projectionModeMatrix.m[13] = 0.5;
  26621. this._projectionModeMatrix.m[14] = 1.0;
  26622. this._projectionModeMatrix.m[15] = 1.0;
  26623. var projectionMatrix = scene.getProjectionMatrix();
  26624. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26625. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26626. break;
  26627. default:
  26628. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26629. break;
  26630. }
  26631. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26632. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26633. });
  26634. return this._cachedTextureMatrix;
  26635. };
  26636. Texture.prototype.clone = function () {
  26637. var _this = this;
  26638. return BABYLON.SerializationHelper.Clone(function () {
  26639. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26640. }, this);
  26641. };
  26642. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26643. get: function () {
  26644. if (!this._onLoadObservable) {
  26645. this._onLoadObservable = new BABYLON.Observable();
  26646. }
  26647. return this._onLoadObservable;
  26648. },
  26649. enumerable: true,
  26650. configurable: true
  26651. });
  26652. Texture.prototype.serialize = function () {
  26653. var serializationObject = _super.prototype.serialize.call(this);
  26654. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26655. serializationObject.base64String = this._buffer;
  26656. serializationObject.name = serializationObject.name.replace("data:", "");
  26657. }
  26658. return serializationObject;
  26659. };
  26660. Texture.prototype.getClassName = function () {
  26661. return "Texture";
  26662. };
  26663. Texture.prototype.dispose = function () {
  26664. _super.prototype.dispose.call(this);
  26665. if (this.onLoadObservable) {
  26666. this.onLoadObservable.clear();
  26667. this._onLoadObservable = null;
  26668. }
  26669. this._delayedOnLoad = null;
  26670. this._delayedOnError = null;
  26671. };
  26672. // Statics
  26673. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26674. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26675. if (onLoad === void 0) { onLoad = null; }
  26676. if (onError === void 0) { onError = null; }
  26677. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26678. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26679. };
  26680. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26681. if (parsedTexture.customType) {
  26682. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26683. // Update Sampling Mode
  26684. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26685. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26686. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  26687. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  26688. }
  26689. }
  26690. return parsedCustomTexture;
  26691. }
  26692. if (parsedTexture.isCube) {
  26693. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26694. }
  26695. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26696. return null;
  26697. }
  26698. var texture = BABYLON.SerializationHelper.Parse(function () {
  26699. var generateMipMaps = true;
  26700. if (parsedTexture.noMipmap) {
  26701. generateMipMaps = false;
  26702. }
  26703. if (parsedTexture.mirrorPlane) {
  26704. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26705. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26706. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26707. return mirrorTexture;
  26708. }
  26709. else if (parsedTexture.isRenderTarget) {
  26710. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26711. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26712. return renderTargetTexture;
  26713. }
  26714. else {
  26715. var texture;
  26716. if (parsedTexture.base64String) {
  26717. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  26718. }
  26719. else {
  26720. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  26721. }
  26722. return texture;
  26723. }
  26724. }, parsedTexture, scene);
  26725. // Update Sampling Mode
  26726. if (parsedTexture.samplingMode) {
  26727. var sampling = parsedTexture.samplingMode;
  26728. if (texture._samplingMode !== sampling) {
  26729. texture.updateSamplingMode(sampling);
  26730. }
  26731. }
  26732. // Animations
  26733. if (parsedTexture.animations) {
  26734. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26735. var parsedAnimation = parsedTexture.animations[animationIndex];
  26736. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26737. }
  26738. }
  26739. return texture;
  26740. };
  26741. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26742. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26743. if (noMipmap === void 0) { noMipmap = false; }
  26744. if (invertY === void 0) { invertY = true; }
  26745. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26746. if (onLoad === void 0) { onLoad = null; }
  26747. if (onError === void 0) { onError = null; }
  26748. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26749. if (name.substr(0, 5) !== "data:") {
  26750. name = "data:" + name;
  26751. }
  26752. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26753. };
  26754. // Constants
  26755. Texture.NEAREST_SAMPLINGMODE = 1;
  26756. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  26757. Texture.BILINEAR_SAMPLINGMODE = 2;
  26758. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  26759. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26760. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  26761. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  26762. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  26763. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  26764. Texture.NEAREST_LINEAR = 7;
  26765. Texture.NEAREST_NEAREST = 8;
  26766. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  26767. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  26768. Texture.LINEAR_LINEAR = 11;
  26769. Texture.LINEAR_NEAREST = 12;
  26770. Texture.EXPLICIT_MODE = 0;
  26771. Texture.SPHERICAL_MODE = 1;
  26772. Texture.PLANAR_MODE = 2;
  26773. Texture.CUBIC_MODE = 3;
  26774. Texture.PROJECTION_MODE = 4;
  26775. Texture.SKYBOX_MODE = 5;
  26776. Texture.INVCUBIC_MODE = 6;
  26777. Texture.EQUIRECTANGULAR_MODE = 7;
  26778. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26779. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  26780. Texture.CLAMP_ADDRESSMODE = 0;
  26781. Texture.WRAP_ADDRESSMODE = 1;
  26782. Texture.MIRROR_ADDRESSMODE = 2;
  26783. __decorate([
  26784. BABYLON.serialize()
  26785. ], Texture.prototype, "url", void 0);
  26786. __decorate([
  26787. BABYLON.serialize()
  26788. ], Texture.prototype, "uOffset", void 0);
  26789. __decorate([
  26790. BABYLON.serialize()
  26791. ], Texture.prototype, "vOffset", void 0);
  26792. __decorate([
  26793. BABYLON.serialize()
  26794. ], Texture.prototype, "uScale", void 0);
  26795. __decorate([
  26796. BABYLON.serialize()
  26797. ], Texture.prototype, "vScale", void 0);
  26798. __decorate([
  26799. BABYLON.serialize()
  26800. ], Texture.prototype, "uAng", void 0);
  26801. __decorate([
  26802. BABYLON.serialize()
  26803. ], Texture.prototype, "vAng", void 0);
  26804. __decorate([
  26805. BABYLON.serialize()
  26806. ], Texture.prototype, "wAng", void 0);
  26807. __decorate([
  26808. BABYLON.serialize()
  26809. ], Texture.prototype, "isBlocking", null);
  26810. return Texture;
  26811. }(BABYLON.BaseTexture));
  26812. BABYLON.Texture = Texture;
  26813. })(BABYLON || (BABYLON = {}));
  26814. //# sourceMappingURL=babylon.texture.js.map
  26815. var BABYLON;
  26816. (function (BABYLON) {
  26817. var _InstancesBatch = /** @class */ (function () {
  26818. function _InstancesBatch() {
  26819. this.mustReturn = false;
  26820. this.visibleInstances = new Array();
  26821. this.renderSelf = new Array();
  26822. }
  26823. return _InstancesBatch;
  26824. }());
  26825. BABYLON._InstancesBatch = _InstancesBatch;
  26826. var Mesh = /** @class */ (function (_super) {
  26827. __extends(Mesh, _super);
  26828. /**
  26829. * @constructor
  26830. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  26831. * @param {Scene} scene The scene to add this mesh to.
  26832. * @param {Node} parent The parent of this mesh, if it has one
  26833. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  26834. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  26835. * When false, achieved by calling a clone(), also passing False.
  26836. * This will make creation of children, recursive.
  26837. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  26838. */
  26839. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  26840. if (scene === void 0) { scene = null; }
  26841. if (parent === void 0) { parent = null; }
  26842. if (source === void 0) { source = null; }
  26843. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26844. var _this = _super.call(this, name, scene) || this;
  26845. // Events
  26846. /**
  26847. * An event triggered before rendering the mesh
  26848. * @type {BABYLON.Observable}
  26849. */
  26850. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26851. /**
  26852. * An event triggered after rendering the mesh
  26853. * @type {BABYLON.Observable}
  26854. */
  26855. _this.onAfterRenderObservable = new BABYLON.Observable();
  26856. /**
  26857. * An event triggered before drawing the mesh
  26858. * @type {BABYLON.Observable}
  26859. */
  26860. _this.onBeforeDrawObservable = new BABYLON.Observable();
  26861. // Members
  26862. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26863. _this.instances = new Array();
  26864. _this._LODLevels = new Array();
  26865. _this._visibleInstances = {};
  26866. _this._renderIdForInstances = new Array();
  26867. _this._batchCache = new _InstancesBatch();
  26868. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26869. // Use by builder only to know what orientation were the mesh build in.
  26870. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  26871. _this.overrideMaterialSideOrientation = null;
  26872. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  26873. // Will be used to save a source mesh reference, If any
  26874. _this._source = null;
  26875. scene = _this.getScene();
  26876. if (source) {
  26877. // Source mesh
  26878. _this._source = source;
  26879. // Geometry
  26880. if (source._geometry) {
  26881. source._geometry.applyToMesh(_this);
  26882. }
  26883. // Deep copy
  26884. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  26885. // Metadata
  26886. if (source.metadata && source.metadata.clone) {
  26887. _this.metadata = source.metadata.clone();
  26888. }
  26889. else {
  26890. _this.metadata = source.metadata;
  26891. }
  26892. // Tags
  26893. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  26894. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  26895. }
  26896. // Parent
  26897. _this.parent = source.parent;
  26898. // Pivot
  26899. _this.setPivotMatrix(source.getPivotMatrix());
  26900. _this.id = name + "." + source.id;
  26901. // Material
  26902. _this.material = source.material;
  26903. var index;
  26904. if (!doNotCloneChildren) {
  26905. // Children
  26906. var directDescendants = source.getDescendants(true);
  26907. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  26908. var child = directDescendants[index_1];
  26909. if (child.clone) {
  26910. child.clone(name + "." + child.name, _this);
  26911. }
  26912. }
  26913. }
  26914. // Physics clone
  26915. var physicsEngine = _this.getScene().getPhysicsEngine();
  26916. if (clonePhysicsImpostor && physicsEngine) {
  26917. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  26918. if (impostor) {
  26919. _this.physicsImpostor = impostor.clone(_this);
  26920. }
  26921. }
  26922. // Particles
  26923. for (index = 0; index < scene.particleSystems.length; index++) {
  26924. var system = scene.particleSystems[index];
  26925. if (system.emitter === source) {
  26926. system.clone(system.name, _this);
  26927. }
  26928. }
  26929. _this.computeWorldMatrix(true);
  26930. }
  26931. // Parent
  26932. if (parent !== null) {
  26933. _this.parent = parent;
  26934. }
  26935. return _this;
  26936. }
  26937. Object.defineProperty(Mesh, "FRONTSIDE", {
  26938. /**
  26939. * Mesh side orientation : usually the external or front surface
  26940. */
  26941. get: function () {
  26942. return Mesh._FRONTSIDE;
  26943. },
  26944. enumerable: true,
  26945. configurable: true
  26946. });
  26947. Object.defineProperty(Mesh, "BACKSIDE", {
  26948. /**
  26949. * Mesh side orientation : usually the internal or back surface
  26950. */
  26951. get: function () {
  26952. return Mesh._BACKSIDE;
  26953. },
  26954. enumerable: true,
  26955. configurable: true
  26956. });
  26957. Object.defineProperty(Mesh, "DOUBLESIDE", {
  26958. /**
  26959. * Mesh side orientation : both internal and external or front and back surfaces
  26960. */
  26961. get: function () {
  26962. return Mesh._DOUBLESIDE;
  26963. },
  26964. enumerable: true,
  26965. configurable: true
  26966. });
  26967. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  26968. /**
  26969. * Mesh side orientation : by default, `FRONTSIDE`
  26970. */
  26971. get: function () {
  26972. return Mesh._DEFAULTSIDE;
  26973. },
  26974. enumerable: true,
  26975. configurable: true
  26976. });
  26977. Object.defineProperty(Mesh, "NO_CAP", {
  26978. /**
  26979. * Mesh cap setting : no cap
  26980. */
  26981. get: function () {
  26982. return Mesh._NO_CAP;
  26983. },
  26984. enumerable: true,
  26985. configurable: true
  26986. });
  26987. Object.defineProperty(Mesh, "CAP_START", {
  26988. /**
  26989. * Mesh cap setting : one cap at the beginning of the mesh
  26990. */
  26991. get: function () {
  26992. return Mesh._CAP_START;
  26993. },
  26994. enumerable: true,
  26995. configurable: true
  26996. });
  26997. Object.defineProperty(Mesh, "CAP_END", {
  26998. /**
  26999. * Mesh cap setting : one cap at the end of the mesh
  27000. */
  27001. get: function () {
  27002. return Mesh._CAP_END;
  27003. },
  27004. enumerable: true,
  27005. configurable: true
  27006. });
  27007. Object.defineProperty(Mesh, "CAP_ALL", {
  27008. /**
  27009. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27010. */
  27011. get: function () {
  27012. return Mesh._CAP_ALL;
  27013. },
  27014. enumerable: true,
  27015. configurable: true
  27016. });
  27017. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27018. set: function (callback) {
  27019. if (this._onBeforeDrawObserver) {
  27020. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27021. }
  27022. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27023. },
  27024. enumerable: true,
  27025. configurable: true
  27026. });
  27027. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27028. get: function () {
  27029. return this._morphTargetManager;
  27030. },
  27031. set: function (value) {
  27032. if (this._morphTargetManager === value) {
  27033. return;
  27034. }
  27035. this._morphTargetManager = value;
  27036. this._syncGeometryWithMorphTargetManager();
  27037. },
  27038. enumerable: true,
  27039. configurable: true
  27040. });
  27041. Object.defineProperty(Mesh.prototype, "source", {
  27042. get: function () {
  27043. return this._source;
  27044. },
  27045. enumerable: true,
  27046. configurable: true
  27047. });
  27048. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27049. get: function () {
  27050. return this._unIndexed;
  27051. },
  27052. set: function (value) {
  27053. if (this._unIndexed !== value) {
  27054. this._unIndexed = value;
  27055. this._markSubMeshesAsAttributesDirty();
  27056. }
  27057. },
  27058. enumerable: true,
  27059. configurable: true
  27060. });
  27061. // Methods
  27062. /**
  27063. * Returns the string "Mesh".
  27064. */
  27065. Mesh.prototype.getClassName = function () {
  27066. return "Mesh";
  27067. };
  27068. /**
  27069. * Returns a string.
  27070. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27071. */
  27072. Mesh.prototype.toString = function (fullDetails) {
  27073. var ret = _super.prototype.toString.call(this, fullDetails);
  27074. ret += ", n vertices: " + this.getTotalVertices();
  27075. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27076. if (this.animations) {
  27077. for (var i = 0; i < this.animations.length; i++) {
  27078. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27079. }
  27080. }
  27081. if (fullDetails) {
  27082. if (this._geometry) {
  27083. var ib = this.getIndices();
  27084. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27085. if (vb && ib) {
  27086. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27087. }
  27088. }
  27089. else {
  27090. ret += ", flat shading: UNKNOWN";
  27091. }
  27092. }
  27093. return ret;
  27094. };
  27095. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27096. /**
  27097. * True if the mesh has some Levels Of Details (LOD).
  27098. * Returns a boolean.
  27099. */
  27100. get: function () {
  27101. return this._LODLevels.length > 0;
  27102. },
  27103. enumerable: true,
  27104. configurable: true
  27105. });
  27106. /**
  27107. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27108. * @returns an array of {BABYLON.MeshLODLevel}
  27109. */
  27110. Mesh.prototype.getLODLevels = function () {
  27111. return this._LODLevels;
  27112. };
  27113. Mesh.prototype._sortLODLevels = function () {
  27114. this._LODLevels.sort(function (a, b) {
  27115. if (a.distance < b.distance) {
  27116. return 1;
  27117. }
  27118. if (a.distance > b.distance) {
  27119. return -1;
  27120. }
  27121. return 0;
  27122. });
  27123. };
  27124. /**
  27125. * Add a mesh as LOD level triggered at the given distance.
  27126. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27127. * @param {number} distance The distance from the center of the object to show this level
  27128. * @param {Mesh} mesh The mesh to be added as LOD level
  27129. * @return {Mesh} This mesh (for chaining)
  27130. */
  27131. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27132. if (mesh && mesh._masterMesh) {
  27133. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27134. return this;
  27135. }
  27136. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27137. this._LODLevels.push(level);
  27138. if (mesh) {
  27139. mesh._masterMesh = this;
  27140. }
  27141. this._sortLODLevels();
  27142. return this;
  27143. };
  27144. /**
  27145. * Returns the LOD level mesh at the passed distance or null if not found.
  27146. * It is related to the method `addLODLevel(distance, mesh)`.
  27147. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27148. * Returns an object Mesh or `null`.
  27149. */
  27150. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27151. for (var index = 0; index < this._LODLevels.length; index++) {
  27152. var level = this._LODLevels[index];
  27153. if (level.distance === distance) {
  27154. return level.mesh;
  27155. }
  27156. }
  27157. return null;
  27158. };
  27159. /**
  27160. * Remove a mesh from the LOD array
  27161. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27162. * @param {Mesh} mesh The mesh to be removed.
  27163. * @return {Mesh} This mesh (for chaining)
  27164. */
  27165. Mesh.prototype.removeLODLevel = function (mesh) {
  27166. for (var index = 0; index < this._LODLevels.length; index++) {
  27167. if (this._LODLevels[index].mesh === mesh) {
  27168. this._LODLevels.splice(index, 1);
  27169. if (mesh) {
  27170. mesh._masterMesh = null;
  27171. }
  27172. }
  27173. }
  27174. this._sortLODLevels();
  27175. return this;
  27176. };
  27177. /**
  27178. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27179. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27180. */
  27181. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27182. if (!this._LODLevels || this._LODLevels.length === 0) {
  27183. return this;
  27184. }
  27185. var bSphere;
  27186. if (boundingSphere) {
  27187. bSphere = boundingSphere;
  27188. }
  27189. else {
  27190. var boundingInfo = this.getBoundingInfo();
  27191. bSphere = boundingInfo.boundingSphere;
  27192. }
  27193. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27194. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27195. if (this.onLODLevelSelection) {
  27196. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27197. }
  27198. return this;
  27199. }
  27200. for (var index = 0; index < this._LODLevels.length; index++) {
  27201. var level = this._LODLevels[index];
  27202. if (level.distance < distanceToCamera) {
  27203. if (level.mesh) {
  27204. level.mesh._preActivate();
  27205. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27206. }
  27207. if (this.onLODLevelSelection) {
  27208. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27209. }
  27210. return level.mesh;
  27211. }
  27212. }
  27213. if (this.onLODLevelSelection) {
  27214. this.onLODLevelSelection(distanceToCamera, this, this);
  27215. }
  27216. return this;
  27217. };
  27218. Object.defineProperty(Mesh.prototype, "geometry", {
  27219. /**
  27220. * Returns the mesh internal Geometry object.
  27221. */
  27222. get: function () {
  27223. return this._geometry;
  27224. },
  27225. enumerable: true,
  27226. configurable: true
  27227. });
  27228. /**
  27229. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27230. */
  27231. Mesh.prototype.getTotalVertices = function () {
  27232. if (this._geometry === null || this._geometry === undefined) {
  27233. return 0;
  27234. }
  27235. return this._geometry.getTotalVertices();
  27236. };
  27237. /**
  27238. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27239. * 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.
  27240. * You can force the copy with forceCopy === true
  27241. * Returns null if the mesh has no geometry or no vertex buffer.
  27242. * Possible `kind` values :
  27243. * - BABYLON.VertexBuffer.PositionKind
  27244. * - BABYLON.VertexBuffer.UVKind
  27245. * - BABYLON.VertexBuffer.UV2Kind
  27246. * - BABYLON.VertexBuffer.UV3Kind
  27247. * - BABYLON.VertexBuffer.UV4Kind
  27248. * - BABYLON.VertexBuffer.UV5Kind
  27249. * - BABYLON.VertexBuffer.UV6Kind
  27250. * - BABYLON.VertexBuffer.ColorKind
  27251. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27252. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27253. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27254. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27255. */
  27256. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27257. if (!this._geometry) {
  27258. return null;
  27259. }
  27260. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27261. };
  27262. /**
  27263. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27264. * Returns `null` if the mesh has no geometry.
  27265. * Possible `kind` values :
  27266. * - BABYLON.VertexBuffer.PositionKind
  27267. * - BABYLON.VertexBuffer.UVKind
  27268. * - BABYLON.VertexBuffer.UV2Kind
  27269. * - BABYLON.VertexBuffer.UV3Kind
  27270. * - BABYLON.VertexBuffer.UV4Kind
  27271. * - BABYLON.VertexBuffer.UV5Kind
  27272. * - BABYLON.VertexBuffer.UV6Kind
  27273. * - BABYLON.VertexBuffer.ColorKind
  27274. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27275. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27276. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27277. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27278. */
  27279. Mesh.prototype.getVertexBuffer = function (kind) {
  27280. if (!this._geometry) {
  27281. return null;
  27282. }
  27283. return this._geometry.getVertexBuffer(kind);
  27284. };
  27285. /**
  27286. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27287. * Possible `kind` values :
  27288. * - BABYLON.VertexBuffer.PositionKind
  27289. * - BABYLON.VertexBuffer.UVKind
  27290. * - BABYLON.VertexBuffer.UV2Kind
  27291. * - BABYLON.VertexBuffer.UV3Kind
  27292. * - BABYLON.VertexBuffer.UV4Kind
  27293. * - BABYLON.VertexBuffer.UV5Kind
  27294. * - BABYLON.VertexBuffer.UV6Kind
  27295. * - BABYLON.VertexBuffer.ColorKind
  27296. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27297. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27298. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27299. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27300. */
  27301. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27302. if (!this._geometry) {
  27303. if (this._delayInfo) {
  27304. return this._delayInfo.indexOf(kind) !== -1;
  27305. }
  27306. return false;
  27307. }
  27308. return this._geometry.isVerticesDataPresent(kind);
  27309. };
  27310. /**
  27311. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27312. * Possible `kind` values :
  27313. * - BABYLON.VertexBuffer.PositionKind
  27314. * - BABYLON.VertexBuffer.UVKind
  27315. * - BABYLON.VertexBuffer.UV2Kind
  27316. * - BABYLON.VertexBuffer.UV3Kind
  27317. * - BABYLON.VertexBuffer.UV4Kind
  27318. * - BABYLON.VertexBuffer.UV5Kind
  27319. * - BABYLON.VertexBuffer.UV6Kind
  27320. * - BABYLON.VertexBuffer.ColorKind
  27321. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27322. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27323. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27324. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27325. */
  27326. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27327. if (!this._geometry) {
  27328. if (this._delayInfo) {
  27329. return this._delayInfo.indexOf(kind) !== -1;
  27330. }
  27331. return false;
  27332. }
  27333. return this._geometry.isVertexBufferUpdatable(kind);
  27334. };
  27335. /**
  27336. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27337. * Possible `kind` values :
  27338. * - BABYLON.VertexBuffer.PositionKind
  27339. * - BABYLON.VertexBuffer.UVKind
  27340. * - BABYLON.VertexBuffer.UV2Kind
  27341. * - BABYLON.VertexBuffer.UV3Kind
  27342. * - BABYLON.VertexBuffer.UV4Kind
  27343. * - BABYLON.VertexBuffer.UV5Kind
  27344. * - BABYLON.VertexBuffer.UV6Kind
  27345. * - BABYLON.VertexBuffer.ColorKind
  27346. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27347. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27348. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27349. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27350. */
  27351. Mesh.prototype.getVerticesDataKinds = function () {
  27352. if (!this._geometry) {
  27353. var result = new Array();
  27354. if (this._delayInfo) {
  27355. this._delayInfo.forEach(function (kind, index, array) {
  27356. result.push(kind);
  27357. });
  27358. }
  27359. return result;
  27360. }
  27361. return this._geometry.getVerticesDataKinds();
  27362. };
  27363. /**
  27364. * Returns a positive integer : the total number of indices in this mesh geometry.
  27365. * Returns zero if the mesh has no geometry.
  27366. */
  27367. Mesh.prototype.getTotalIndices = function () {
  27368. if (!this._geometry) {
  27369. return 0;
  27370. }
  27371. return this._geometry.getTotalIndices();
  27372. };
  27373. /**
  27374. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27375. * 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.
  27376. * Returns an empty array if the mesh has no geometry.
  27377. */
  27378. Mesh.prototype.getIndices = function (copyWhenShared) {
  27379. if (!this._geometry) {
  27380. return [];
  27381. }
  27382. return this._geometry.getIndices(copyWhenShared);
  27383. };
  27384. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27385. get: function () {
  27386. return this._masterMesh !== null && this._masterMesh !== undefined;
  27387. },
  27388. enumerable: true,
  27389. configurable: true
  27390. });
  27391. /**
  27392. * Determine if the current mesh is ready to be rendered
  27393. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27394. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27395. * @returns true if all associated assets are ready (material, textures, shaders)
  27396. */
  27397. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27398. if (completeCheck === void 0) { completeCheck = false; }
  27399. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27400. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27401. return false;
  27402. }
  27403. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27404. return false;
  27405. }
  27406. if (!this.subMeshes || this.subMeshes.length === 0) {
  27407. return true;
  27408. }
  27409. if (!completeCheck) {
  27410. return true;
  27411. }
  27412. var engine = this.getEngine();
  27413. var scene = this.getScene();
  27414. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27415. this.computeWorldMatrix();
  27416. var mat = this.material || scene.defaultMaterial;
  27417. if (mat) {
  27418. if (mat.storeEffectOnSubMeshes) {
  27419. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27420. var subMesh = _a[_i];
  27421. var effectiveMaterial = subMesh.getMaterial();
  27422. if (effectiveMaterial) {
  27423. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27424. return false;
  27425. }
  27426. }
  27427. }
  27428. }
  27429. else {
  27430. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27431. return false;
  27432. }
  27433. }
  27434. }
  27435. // Shadows
  27436. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27437. var light = _c[_b];
  27438. var generator = light.getShadowGenerator();
  27439. if (generator) {
  27440. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27441. var subMesh = _e[_d];
  27442. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27443. return false;
  27444. }
  27445. }
  27446. }
  27447. }
  27448. // LOD
  27449. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27450. var lod = _g[_f];
  27451. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27452. return false;
  27453. }
  27454. }
  27455. return true;
  27456. };
  27457. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27458. /**
  27459. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27460. * This property is pertinent only for updatable parametric shapes.
  27461. */
  27462. get: function () {
  27463. return this._areNormalsFrozen;
  27464. },
  27465. enumerable: true,
  27466. configurable: true
  27467. });
  27468. /**
  27469. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27470. * It has no effect at all on other shapes.
  27471. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27472. * Returns the Mesh.
  27473. */
  27474. Mesh.prototype.freezeNormals = function () {
  27475. this._areNormalsFrozen = true;
  27476. return this;
  27477. };
  27478. /**
  27479. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27480. * It has no effect at all on other shapes.
  27481. * It reactivates the mesh normals computation if it was previously frozen.
  27482. * Returns the Mesh.
  27483. */
  27484. Mesh.prototype.unfreezeNormals = function () {
  27485. this._areNormalsFrozen = false;
  27486. return this;
  27487. };
  27488. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27489. /**
  27490. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27491. */
  27492. set: function (count) {
  27493. this._overridenInstanceCount = count;
  27494. },
  27495. enumerable: true,
  27496. configurable: true
  27497. });
  27498. // Methods
  27499. Mesh.prototype._preActivate = function () {
  27500. var sceneRenderId = this.getScene().getRenderId();
  27501. if (this._preActivateId === sceneRenderId) {
  27502. return this;
  27503. }
  27504. this._preActivateId = sceneRenderId;
  27505. this._visibleInstances = null;
  27506. return this;
  27507. };
  27508. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27509. if (this._visibleInstances) {
  27510. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27511. }
  27512. return this;
  27513. };
  27514. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27515. if (!this._visibleInstances) {
  27516. this._visibleInstances = {};
  27517. this._visibleInstances.defaultRenderId = renderId;
  27518. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27519. }
  27520. if (!this._visibleInstances[renderId]) {
  27521. this._visibleInstances[renderId] = new Array();
  27522. }
  27523. this._visibleInstances[renderId].push(instance);
  27524. return this;
  27525. };
  27526. /**
  27527. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27528. * This means the mesh underlying bounding box and sphere are recomputed.
  27529. * Returns the Mesh.
  27530. */
  27531. Mesh.prototype.refreshBoundingInfo = function () {
  27532. return this._refreshBoundingInfo(false);
  27533. };
  27534. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27535. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27536. return this;
  27537. }
  27538. var data = this._getPositionData(applySkeleton);
  27539. if (data) {
  27540. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27541. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27542. }
  27543. if (this.subMeshes) {
  27544. for (var index = 0; index < this.subMeshes.length; index++) {
  27545. this.subMeshes[index].refreshBoundingInfo();
  27546. }
  27547. }
  27548. this._updateBoundingInfo();
  27549. return this;
  27550. };
  27551. Mesh.prototype._getPositionData = function (applySkeleton) {
  27552. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27553. if (data && applySkeleton && this.skeleton) {
  27554. data = BABYLON.Tools.Slice(data);
  27555. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27556. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27557. if (matricesWeightsData && matricesIndicesData) {
  27558. var needExtras = this.numBoneInfluencers > 4;
  27559. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27560. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27561. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27562. var tempVector = BABYLON.Tmp.Vector3[0];
  27563. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27564. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27565. var matWeightIdx = 0;
  27566. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27567. finalMatrix.reset();
  27568. var inf;
  27569. var weight;
  27570. for (inf = 0; inf < 4; inf++) {
  27571. weight = matricesWeightsData[matWeightIdx + inf];
  27572. if (weight <= 0)
  27573. break;
  27574. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27575. finalMatrix.addToSelf(tempMatrix);
  27576. }
  27577. if (needExtras) {
  27578. for (inf = 0; inf < 4; inf++) {
  27579. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27580. if (weight <= 0)
  27581. break;
  27582. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27583. finalMatrix.addToSelf(tempMatrix);
  27584. }
  27585. }
  27586. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27587. tempVector.toArray(data, index);
  27588. }
  27589. }
  27590. }
  27591. return data;
  27592. };
  27593. Mesh.prototype._createGlobalSubMesh = function (force) {
  27594. var totalVertices = this.getTotalVertices();
  27595. if (!totalVertices || !this.getIndices()) {
  27596. return null;
  27597. }
  27598. // Check if we need to recreate the submeshes
  27599. if (this.subMeshes && this.subMeshes.length > 0) {
  27600. var ib = this.getIndices();
  27601. if (!ib) {
  27602. return null;
  27603. }
  27604. var totalIndices = ib.length;
  27605. var needToRecreate = false;
  27606. if (force) {
  27607. needToRecreate = true;
  27608. }
  27609. else {
  27610. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27611. var submesh = _a[_i];
  27612. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27613. needToRecreate = true;
  27614. break;
  27615. }
  27616. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27617. needToRecreate = true;
  27618. break;
  27619. }
  27620. }
  27621. }
  27622. if (!needToRecreate) {
  27623. return this.subMeshes[0];
  27624. }
  27625. }
  27626. this.releaseSubMeshes();
  27627. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27628. };
  27629. Mesh.prototype.subdivide = function (count) {
  27630. if (count < 1) {
  27631. return;
  27632. }
  27633. var totalIndices = this.getTotalIndices();
  27634. var subdivisionSize = (totalIndices / count) | 0;
  27635. var offset = 0;
  27636. // Ensure that subdivisionSize is a multiple of 3
  27637. while (subdivisionSize % 3 !== 0) {
  27638. subdivisionSize++;
  27639. }
  27640. this.releaseSubMeshes();
  27641. for (var index = 0; index < count; index++) {
  27642. if (offset >= totalIndices) {
  27643. break;
  27644. }
  27645. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27646. offset += subdivisionSize;
  27647. }
  27648. this.synchronizeInstances();
  27649. };
  27650. /**
  27651. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27652. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27653. * The `data` are either a numeric array either a Float32Array.
  27654. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27655. * 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).
  27656. * Note that a new underlying VertexBuffer object is created each call.
  27657. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27658. *
  27659. * Possible `kind` values :
  27660. * - BABYLON.VertexBuffer.PositionKind
  27661. * - BABYLON.VertexBuffer.UVKind
  27662. * - BABYLON.VertexBuffer.UV2Kind
  27663. * - BABYLON.VertexBuffer.UV3Kind
  27664. * - BABYLON.VertexBuffer.UV4Kind
  27665. * - BABYLON.VertexBuffer.UV5Kind
  27666. * - BABYLON.VertexBuffer.UV6Kind
  27667. * - BABYLON.VertexBuffer.ColorKind
  27668. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27669. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27670. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27671. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27672. *
  27673. * Returns the Mesh.
  27674. */
  27675. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27676. if (updatable === void 0) { updatable = false; }
  27677. if (!this._geometry) {
  27678. var vertexData = new BABYLON.VertexData();
  27679. vertexData.set(data, kind);
  27680. var scene = this.getScene();
  27681. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27682. }
  27683. else {
  27684. this._geometry.setVerticesData(kind, data, updatable, stride);
  27685. }
  27686. return this;
  27687. };
  27688. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  27689. if (updatable === void 0) { updatable = true; }
  27690. var vb = this.getVertexBuffer(kind);
  27691. if (!vb || vb.isUpdatable() === updatable) {
  27692. return;
  27693. }
  27694. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  27695. };
  27696. /**
  27697. * Sets the mesh VertexBuffer.
  27698. * Returns the Mesh.
  27699. */
  27700. Mesh.prototype.setVerticesBuffer = function (buffer) {
  27701. if (!this._geometry) {
  27702. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  27703. }
  27704. this._geometry.setVerticesBuffer(buffer);
  27705. return this;
  27706. };
  27707. /**
  27708. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  27709. * If the mesh has no geometry, it is simply returned as it is.
  27710. * The `data` are either a numeric array either a Float32Array.
  27711. * No new underlying VertexBuffer object is created.
  27712. * 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.
  27713. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  27714. *
  27715. * Possible `kind` values :
  27716. * - BABYLON.VertexBuffer.PositionKind
  27717. * - BABYLON.VertexBuffer.UVKind
  27718. * - BABYLON.VertexBuffer.UV2Kind
  27719. * - BABYLON.VertexBuffer.UV3Kind
  27720. * - BABYLON.VertexBuffer.UV4Kind
  27721. * - BABYLON.VertexBuffer.UV5Kind
  27722. * - BABYLON.VertexBuffer.UV6Kind
  27723. * - BABYLON.VertexBuffer.ColorKind
  27724. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27725. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27726. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27727. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27728. *
  27729. * Returns the Mesh.
  27730. */
  27731. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  27732. if (!this._geometry) {
  27733. return this;
  27734. }
  27735. if (!makeItUnique) {
  27736. this._geometry.updateVerticesData(kind, data, updateExtends);
  27737. }
  27738. else {
  27739. this.makeGeometryUnique();
  27740. this.updateVerticesData(kind, data, updateExtends, false);
  27741. }
  27742. return this;
  27743. };
  27744. /**
  27745. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  27746. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  27747. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  27748. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  27749. * Returns the Mesh.
  27750. */
  27751. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  27752. if (computeNormals === void 0) { computeNormals = true; }
  27753. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27754. if (!positions) {
  27755. return this;
  27756. }
  27757. positionFunction(positions);
  27758. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  27759. if (computeNormals) {
  27760. var indices = this.getIndices();
  27761. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27762. if (!normals) {
  27763. return this;
  27764. }
  27765. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  27766. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  27767. }
  27768. return this;
  27769. };
  27770. /**
  27771. * Creates a un-shared specific occurence of the geometry for the mesh.
  27772. * Returns the Mesh.
  27773. */
  27774. Mesh.prototype.makeGeometryUnique = function () {
  27775. if (!this._geometry) {
  27776. return this;
  27777. }
  27778. var oldGeometry = this._geometry;
  27779. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  27780. oldGeometry.releaseForMesh(this, true);
  27781. geometry.applyToMesh(this);
  27782. return this;
  27783. };
  27784. /**
  27785. * Sets the mesh indices.
  27786. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  27787. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  27788. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  27789. * This method creates a new index buffer each call.
  27790. * Returns the Mesh.
  27791. */
  27792. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  27793. if (totalVertices === void 0) { totalVertices = null; }
  27794. if (updatable === void 0) { updatable = false; }
  27795. if (!this._geometry) {
  27796. var vertexData = new BABYLON.VertexData();
  27797. vertexData.indices = indices;
  27798. var scene = this.getScene();
  27799. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27800. }
  27801. else {
  27802. this._geometry.setIndices(indices, totalVertices, updatable);
  27803. }
  27804. return this;
  27805. };
  27806. /**
  27807. * Update the current index buffer
  27808. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  27809. * Returns the Mesh.
  27810. */
  27811. Mesh.prototype.updateIndices = function (indices, offset) {
  27812. if (!this._geometry) {
  27813. return this;
  27814. }
  27815. this._geometry.updateIndices(indices, offset);
  27816. return this;
  27817. };
  27818. /**
  27819. * Invert the geometry to move from a right handed system to a left handed one.
  27820. * Returns the Mesh.
  27821. */
  27822. Mesh.prototype.toLeftHanded = function () {
  27823. if (!this._geometry) {
  27824. return this;
  27825. }
  27826. this._geometry.toLeftHanded();
  27827. return this;
  27828. };
  27829. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  27830. if (!this._geometry) {
  27831. return this;
  27832. }
  27833. var engine = this.getScene().getEngine();
  27834. // Wireframe
  27835. var indexToBind;
  27836. if (this._unIndexed) {
  27837. indexToBind = null;
  27838. }
  27839. else {
  27840. switch (fillMode) {
  27841. case BABYLON.Material.PointFillMode:
  27842. indexToBind = null;
  27843. break;
  27844. case BABYLON.Material.WireFrameFillMode:
  27845. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  27846. break;
  27847. default:
  27848. case BABYLON.Material.TriangleFillMode:
  27849. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  27850. break;
  27851. }
  27852. }
  27853. // VBOs
  27854. this._geometry._bind(effect, indexToBind);
  27855. return this;
  27856. };
  27857. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  27858. if (alternate === void 0) { alternate = false; }
  27859. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27860. return this;
  27861. }
  27862. this.onBeforeDrawObservable.notifyObservers(this);
  27863. var scene = this.getScene();
  27864. var engine = scene.getEngine();
  27865. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  27866. // or triangles as points
  27867. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  27868. }
  27869. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  27870. // Triangles as wireframe
  27871. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  27872. }
  27873. else {
  27874. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  27875. }
  27876. if (scene._isAlternateRenderingEnabled && !alternate) {
  27877. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  27878. if (!effect || !scene.activeCamera) {
  27879. return this;
  27880. }
  27881. scene._switchToAlternateCameraConfiguration(true);
  27882. this._effectiveMaterial.bindView(effect);
  27883. this._effectiveMaterial.bindViewProjection(effect);
  27884. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  27885. this._draw(subMesh, fillMode, instancesCount, true);
  27886. engine.setViewport(scene.activeCamera.viewport);
  27887. scene._switchToAlternateCameraConfiguration(false);
  27888. this._effectiveMaterial.bindView(effect);
  27889. this._effectiveMaterial.bindViewProjection(effect);
  27890. }
  27891. return this;
  27892. };
  27893. /**
  27894. * Registers for this mesh a javascript function called just before the rendering process.
  27895. * This function is passed the current mesh.
  27896. * Return the Mesh.
  27897. */
  27898. Mesh.prototype.registerBeforeRender = function (func) {
  27899. this.onBeforeRenderObservable.add(func);
  27900. return this;
  27901. };
  27902. /**
  27903. * Disposes a previously registered javascript function called before the rendering.
  27904. * This function is passed the current mesh.
  27905. * Returns the Mesh.
  27906. */
  27907. Mesh.prototype.unregisterBeforeRender = function (func) {
  27908. this.onBeforeRenderObservable.removeCallback(func);
  27909. return this;
  27910. };
  27911. /**
  27912. * Registers for this mesh a javascript function called just after the rendering is complete.
  27913. * This function is passed the current mesh.
  27914. * Returns the Mesh.
  27915. */
  27916. Mesh.prototype.registerAfterRender = function (func) {
  27917. this.onAfterRenderObservable.add(func);
  27918. return this;
  27919. };
  27920. /**
  27921. * Disposes a previously registered javascript function called after the rendering.
  27922. * This function is passed the current mesh.
  27923. * Return the Mesh.
  27924. */
  27925. Mesh.prototype.unregisterAfterRender = function (func) {
  27926. this.onAfterRenderObservable.removeCallback(func);
  27927. return this;
  27928. };
  27929. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  27930. var scene = this.getScene();
  27931. this._batchCache.mustReturn = false;
  27932. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  27933. this._batchCache.visibleInstances[subMeshId] = null;
  27934. if (this._visibleInstances) {
  27935. var currentRenderId = scene.getRenderId();
  27936. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  27937. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  27938. var selfRenderId = this._renderId;
  27939. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  27940. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  27941. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  27942. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  27943. }
  27944. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  27945. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  27946. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  27947. this._batchCache.mustReturn = true;
  27948. return this._batchCache;
  27949. }
  27950. if (currentRenderId !== selfRenderId) {
  27951. this._batchCache.renderSelf[subMeshId] = false;
  27952. }
  27953. }
  27954. this._renderIdForInstances[subMeshId] = currentRenderId;
  27955. }
  27956. return this._batchCache;
  27957. };
  27958. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  27959. var visibleInstances = batch.visibleInstances[subMesh._id];
  27960. if (!visibleInstances) {
  27961. return this;
  27962. }
  27963. var matricesCount = visibleInstances.length + 1;
  27964. var bufferSize = matricesCount * 16 * 4;
  27965. var currentInstancesBufferSize = this._instancesBufferSize;
  27966. var instancesBuffer = this._instancesBuffer;
  27967. while (this._instancesBufferSize < bufferSize) {
  27968. this._instancesBufferSize *= 2;
  27969. }
  27970. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  27971. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  27972. }
  27973. var offset = 0;
  27974. var instancesCount = 0;
  27975. var world = this.getWorldMatrix();
  27976. if (batch.renderSelf[subMesh._id]) {
  27977. world.copyToArray(this._instancesData, offset);
  27978. offset += 16;
  27979. instancesCount++;
  27980. }
  27981. if (visibleInstances) {
  27982. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  27983. var instance = visibleInstances[instanceIndex];
  27984. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  27985. offset += 16;
  27986. instancesCount++;
  27987. }
  27988. }
  27989. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  27990. if (instancesBuffer) {
  27991. instancesBuffer.dispose();
  27992. }
  27993. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  27994. this._instancesBuffer = instancesBuffer;
  27995. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  27996. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  27997. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  27998. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  27999. }
  28000. else {
  28001. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28002. }
  28003. this._bind(subMesh, effect, fillMode);
  28004. this._draw(subMesh, fillMode, instancesCount);
  28005. engine.unbindInstanceAttributes();
  28006. return this;
  28007. };
  28008. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28009. var scene = this.getScene();
  28010. var engine = scene.getEngine();
  28011. if (hardwareInstancedRendering) {
  28012. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28013. }
  28014. else {
  28015. if (batch.renderSelf[subMesh._id]) {
  28016. // Draw
  28017. if (onBeforeDraw) {
  28018. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28019. }
  28020. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28021. }
  28022. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28023. if (visibleInstancesForSubMesh) {
  28024. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28025. var instance = visibleInstancesForSubMesh[instanceIndex];
  28026. // World
  28027. var world = instance.getWorldMatrix();
  28028. if (onBeforeDraw) {
  28029. onBeforeDraw(true, world, effectiveMaterial);
  28030. }
  28031. // Draw
  28032. this._draw(subMesh, fillMode);
  28033. }
  28034. }
  28035. }
  28036. return this;
  28037. };
  28038. /**
  28039. * Triggers the draw call for the mesh.
  28040. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28041. * Returns the Mesh.
  28042. */
  28043. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28044. this.checkOcclusionQuery();
  28045. if (this._isOccluded) {
  28046. return this;
  28047. }
  28048. var scene = this.getScene();
  28049. // Managing instances
  28050. var batch = this._getInstancesRenderList(subMesh._id);
  28051. if (batch.mustReturn) {
  28052. return this;
  28053. }
  28054. // Checking geometry state
  28055. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28056. return this;
  28057. }
  28058. this.onBeforeRenderObservable.notifyObservers(this);
  28059. var engine = scene.getEngine();
  28060. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28061. // Material
  28062. var material = subMesh.getMaterial();
  28063. if (!material) {
  28064. return this;
  28065. }
  28066. this._effectiveMaterial = material;
  28067. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28068. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28069. return this;
  28070. }
  28071. }
  28072. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28073. return this;
  28074. }
  28075. // Alpha mode
  28076. if (enableAlphaMode) {
  28077. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28078. }
  28079. // Outline - step 1
  28080. var savedDepthWrite = engine.getDepthWrite();
  28081. if (this.renderOutline) {
  28082. engine.setDepthWrite(false);
  28083. scene.getOutlineRenderer().render(subMesh, batch);
  28084. engine.setDepthWrite(savedDepthWrite);
  28085. }
  28086. var effect;
  28087. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28088. effect = subMesh.effect;
  28089. }
  28090. else {
  28091. effect = this._effectiveMaterial.getEffect();
  28092. }
  28093. if (!effect) {
  28094. return this;
  28095. }
  28096. var sideOrientation = this.overrideMaterialSideOrientation;
  28097. if (sideOrientation == null) {
  28098. sideOrientation = this._effectiveMaterial.sideOrientation;
  28099. if (this._getWorldMatrixDeterminant() < 0) {
  28100. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28101. }
  28102. }
  28103. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28104. if (this._effectiveMaterial.forceDepthWrite) {
  28105. engine.setDepthWrite(true);
  28106. }
  28107. // Bind
  28108. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28109. if (!hardwareInstancedRendering) {
  28110. this._bind(subMesh, effect, fillMode);
  28111. }
  28112. var world = this.getWorldMatrix();
  28113. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28114. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28115. }
  28116. else {
  28117. this._effectiveMaterial.bind(world, this);
  28118. }
  28119. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28120. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28121. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28122. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28123. }
  28124. // Draw
  28125. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28126. // Unbind
  28127. this._effectiveMaterial.unbind();
  28128. // Outline - step 2
  28129. if (this.renderOutline && savedDepthWrite) {
  28130. engine.setDepthWrite(true);
  28131. engine.setColorWrite(false);
  28132. scene.getOutlineRenderer().render(subMesh, batch);
  28133. engine.setColorWrite(true);
  28134. }
  28135. // Overlay
  28136. if (this.renderOverlay) {
  28137. var currentMode = engine.getAlphaMode();
  28138. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28139. scene.getOutlineRenderer().render(subMesh, batch, true);
  28140. engine.setAlphaMode(currentMode);
  28141. }
  28142. this.onAfterRenderObservable.notifyObservers(this);
  28143. return this;
  28144. };
  28145. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28146. if (isInstance && effectiveMaterial) {
  28147. effectiveMaterial.bindOnlyWorldMatrix(world);
  28148. }
  28149. };
  28150. /**
  28151. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28152. */
  28153. Mesh.prototype.getEmittedParticleSystems = function () {
  28154. var results = new Array();
  28155. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28156. var particleSystem = this.getScene().particleSystems[index];
  28157. if (particleSystem.emitter === this) {
  28158. results.push(particleSystem);
  28159. }
  28160. }
  28161. return results;
  28162. };
  28163. /**
  28164. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28165. */
  28166. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28167. var results = new Array();
  28168. var descendants = this.getDescendants();
  28169. descendants.push(this);
  28170. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28171. var particleSystem = this.getScene().particleSystems[index];
  28172. var emitter = particleSystem.emitter;
  28173. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28174. results.push(particleSystem);
  28175. }
  28176. }
  28177. return results;
  28178. };
  28179. Mesh.prototype._checkDelayState = function () {
  28180. var scene = this.getScene();
  28181. if (this._geometry) {
  28182. this._geometry.load(scene);
  28183. }
  28184. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28185. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28186. this._queueLoad(scene);
  28187. }
  28188. return this;
  28189. };
  28190. Mesh.prototype._queueLoad = function (scene) {
  28191. var _this = this;
  28192. scene._addPendingData(this);
  28193. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28194. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28195. if (data instanceof ArrayBuffer) {
  28196. _this._delayLoadingFunction(data, _this);
  28197. }
  28198. else {
  28199. _this._delayLoadingFunction(JSON.parse(data), _this);
  28200. }
  28201. _this.instances.forEach(function (instance) {
  28202. instance._syncSubMeshes();
  28203. });
  28204. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28205. scene._removePendingData(_this);
  28206. }, function () { }, scene.database, getBinaryData);
  28207. return this;
  28208. };
  28209. /**
  28210. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28211. */
  28212. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28213. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28214. return false;
  28215. }
  28216. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28217. return false;
  28218. }
  28219. this._checkDelayState();
  28220. return true;
  28221. };
  28222. /**
  28223. * Sets the mesh material by the material or multiMaterial `id` property.
  28224. * The material `id` is a string identifying the material or the multiMaterial.
  28225. * This method returns the Mesh.
  28226. */
  28227. Mesh.prototype.setMaterialByID = function (id) {
  28228. var materials = this.getScene().materials;
  28229. var index;
  28230. for (index = materials.length - 1; index > -1; index--) {
  28231. if (materials[index].id === id) {
  28232. this.material = materials[index];
  28233. return this;
  28234. }
  28235. }
  28236. // Multi
  28237. var multiMaterials = this.getScene().multiMaterials;
  28238. for (index = multiMaterials.length - 1; index > -1; index--) {
  28239. if (multiMaterials[index].id === id) {
  28240. this.material = multiMaterials[index];
  28241. return this;
  28242. }
  28243. }
  28244. return this;
  28245. };
  28246. /**
  28247. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28248. */
  28249. Mesh.prototype.getAnimatables = function () {
  28250. var results = new Array();
  28251. if (this.material) {
  28252. results.push(this.material);
  28253. }
  28254. if (this.skeleton) {
  28255. results.push(this.skeleton);
  28256. }
  28257. return results;
  28258. };
  28259. /**
  28260. * Modifies the mesh geometry according to the passed transformation matrix.
  28261. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28262. * The mesh normals are modified accordingly the same transformation.
  28263. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28264. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28265. * Returns the Mesh.
  28266. */
  28267. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28268. // Position
  28269. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28270. return this;
  28271. }
  28272. var submeshes = this.subMeshes.splice(0);
  28273. this._resetPointsArrayCache();
  28274. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28275. var temp = new Array();
  28276. var index;
  28277. for (index = 0; index < data.length; index += 3) {
  28278. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28279. }
  28280. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28281. // Normals
  28282. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28283. return this;
  28284. }
  28285. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28286. temp = [];
  28287. for (index = 0; index < data.length; index += 3) {
  28288. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28289. }
  28290. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28291. // flip faces?
  28292. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28293. this.flipFaces();
  28294. }
  28295. // Restore submeshes
  28296. this.releaseSubMeshes();
  28297. this.subMeshes = submeshes;
  28298. return this;
  28299. };
  28300. /**
  28301. * Modifies the mesh geometry according to its own current World Matrix.
  28302. * The mesh World Matrix is then reset.
  28303. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28304. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28305. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28306. * Returns the Mesh.
  28307. */
  28308. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28309. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28310. this.scaling.copyFromFloats(1, 1, 1);
  28311. this.position.copyFromFloats(0, 0, 0);
  28312. this.rotation.copyFromFloats(0, 0, 0);
  28313. //only if quaternion is already set
  28314. if (this.rotationQuaternion) {
  28315. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28316. }
  28317. this._worldMatrix = BABYLON.Matrix.Identity();
  28318. return this;
  28319. };
  28320. Object.defineProperty(Mesh.prototype, "_positions", {
  28321. // Cache
  28322. get: function () {
  28323. if (this._geometry) {
  28324. return this._geometry._positions;
  28325. }
  28326. return null;
  28327. },
  28328. enumerable: true,
  28329. configurable: true
  28330. });
  28331. Mesh.prototype._resetPointsArrayCache = function () {
  28332. if (this._geometry) {
  28333. this._geometry._resetPointsArrayCache();
  28334. }
  28335. return this;
  28336. };
  28337. Mesh.prototype._generatePointsArray = function () {
  28338. if (this._geometry) {
  28339. return this._geometry._generatePointsArray();
  28340. }
  28341. return false;
  28342. };
  28343. /**
  28344. * Returns a new Mesh object generated from the current mesh properties.
  28345. * This method must not get confused with createInstance().
  28346. * The parameter `name` is a string, the name given to the new mesh.
  28347. * The optional parameter `newParent` can be any Node object (default `null`).
  28348. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28349. * 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.
  28350. */
  28351. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28352. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28353. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28354. };
  28355. /**
  28356. * Disposes the Mesh.
  28357. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28358. * Returns nothing.
  28359. */
  28360. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28361. var _this = this;
  28362. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28363. this.morphTargetManager = null;
  28364. if (this._geometry) {
  28365. this._geometry.releaseForMesh(this, true);
  28366. }
  28367. // Sources
  28368. var meshes = this.getScene().meshes;
  28369. meshes.forEach(function (abstractMesh) {
  28370. var mesh = abstractMesh;
  28371. if (mesh._source && mesh._source === _this) {
  28372. mesh._source = null;
  28373. }
  28374. });
  28375. this._source = null;
  28376. // Instances
  28377. if (this._instancesBuffer) {
  28378. this._instancesBuffer.dispose();
  28379. this._instancesBuffer = null;
  28380. }
  28381. while (this.instances.length) {
  28382. this.instances[0].dispose();
  28383. }
  28384. // Effect layers.
  28385. var effectLayers = this.getScene().effectLayers;
  28386. for (var i = 0; i < effectLayers.length; i++) {
  28387. var effectLayer = effectLayers[i];
  28388. if (effectLayer) {
  28389. effectLayer._disposeMesh(this);
  28390. }
  28391. }
  28392. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28393. };
  28394. /**
  28395. * Modifies the mesh geometry according to a displacement map.
  28396. * 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.
  28397. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28398. * This method returns nothing.
  28399. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28400. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28401. * 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.
  28402. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28403. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28404. *
  28405. * Returns the Mesh.
  28406. */
  28407. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28408. var _this = this;
  28409. var scene = this.getScene();
  28410. var onload = function (img) {
  28411. // Getting height map data
  28412. var canvas = document.createElement("canvas");
  28413. var context = canvas.getContext("2d");
  28414. var heightMapWidth = img.width;
  28415. var heightMapHeight = img.height;
  28416. canvas.width = heightMapWidth;
  28417. canvas.height = heightMapHeight;
  28418. context.drawImage(img, 0, 0);
  28419. // Create VertexData from map data
  28420. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28421. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28422. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28423. //execute success callback, if set
  28424. if (onSuccess) {
  28425. onSuccess(_this);
  28426. }
  28427. };
  28428. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28429. return this;
  28430. };
  28431. /**
  28432. * Modifies the mesh geometry according to a displacementMap buffer.
  28433. * 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.
  28434. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28435. * This method returns nothing.
  28436. * 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.
  28437. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28438. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28439. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28440. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28441. *
  28442. * Returns the Mesh.
  28443. */
  28444. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28445. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28446. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28447. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28448. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28449. return this;
  28450. }
  28451. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28452. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28453. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28454. var position = BABYLON.Vector3.Zero();
  28455. var normal = BABYLON.Vector3.Zero();
  28456. var uv = BABYLON.Vector2.Zero();
  28457. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28458. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28459. for (var index = 0; index < positions.length; index += 3) {
  28460. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28461. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28462. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28463. // Compute height
  28464. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28465. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28466. var pos = (u + v * heightMapWidth) * 4;
  28467. var r = buffer[pos] / 255.0;
  28468. var g = buffer[pos + 1] / 255.0;
  28469. var b = buffer[pos + 2] / 255.0;
  28470. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28471. normal.normalize();
  28472. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28473. position = position.add(normal);
  28474. position.toArray(positions, index);
  28475. }
  28476. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28477. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28478. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28479. return this;
  28480. };
  28481. /**
  28482. * Modify the mesh to get a flat shading rendering.
  28483. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28484. * This method returns the Mesh.
  28485. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28486. */
  28487. Mesh.prototype.convertToFlatShadedMesh = function () {
  28488. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28489. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28490. var kinds = this.getVerticesDataKinds();
  28491. var vbs = {};
  28492. var data = {};
  28493. var newdata = {};
  28494. var updatableNormals = false;
  28495. var kindIndex;
  28496. var kind;
  28497. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28498. kind = kinds[kindIndex];
  28499. var vertexBuffer = this.getVertexBuffer(kind);
  28500. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28501. updatableNormals = vertexBuffer.isUpdatable();
  28502. kinds.splice(kindIndex, 1);
  28503. kindIndex--;
  28504. continue;
  28505. }
  28506. vbs[kind] = vertexBuffer;
  28507. data[kind] = vbs[kind].getData();
  28508. newdata[kind] = [];
  28509. }
  28510. // Save previous submeshes
  28511. var previousSubmeshes = this.subMeshes.slice(0);
  28512. var indices = this.getIndices();
  28513. var totalIndices = this.getTotalIndices();
  28514. // Generating unique vertices per face
  28515. var index;
  28516. for (index = 0; index < totalIndices; index++) {
  28517. var vertexIndex = indices[index];
  28518. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28519. kind = kinds[kindIndex];
  28520. var stride = vbs[kind].getStrideSize();
  28521. for (var offset = 0; offset < stride; offset++) {
  28522. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28523. }
  28524. }
  28525. }
  28526. // Updating faces & normal
  28527. var normals = [];
  28528. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28529. for (index = 0; index < totalIndices; index += 3) {
  28530. indices[index] = index;
  28531. indices[index + 1] = index + 1;
  28532. indices[index + 2] = index + 2;
  28533. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28534. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28535. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28536. var p1p2 = p1.subtract(p2);
  28537. var p3p2 = p3.subtract(p2);
  28538. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28539. // Store same normals for every vertex
  28540. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28541. normals.push(normal.x);
  28542. normals.push(normal.y);
  28543. normals.push(normal.z);
  28544. }
  28545. }
  28546. this.setIndices(indices);
  28547. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28548. // Updating vertex buffers
  28549. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28550. kind = kinds[kindIndex];
  28551. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28552. }
  28553. // Updating submeshes
  28554. this.releaseSubMeshes();
  28555. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28556. var previousOne = previousSubmeshes[submeshIndex];
  28557. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28558. }
  28559. this.synchronizeInstances();
  28560. return this;
  28561. };
  28562. /**
  28563. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28564. * In other words, more vertices, no more indices and a single bigger VBO.
  28565. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28566. * Returns the Mesh.
  28567. */
  28568. Mesh.prototype.convertToUnIndexedMesh = function () {
  28569. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28570. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28571. var kinds = this.getVerticesDataKinds();
  28572. var vbs = {};
  28573. var data = {};
  28574. var newdata = {};
  28575. var kindIndex;
  28576. var kind;
  28577. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28578. kind = kinds[kindIndex];
  28579. var vertexBuffer = this.getVertexBuffer(kind);
  28580. vbs[kind] = vertexBuffer;
  28581. data[kind] = vbs[kind].getData();
  28582. newdata[kind] = [];
  28583. }
  28584. // Save previous submeshes
  28585. var previousSubmeshes = this.subMeshes.slice(0);
  28586. var indices = this.getIndices();
  28587. var totalIndices = this.getTotalIndices();
  28588. // Generating unique vertices per face
  28589. var index;
  28590. for (index = 0; index < totalIndices; index++) {
  28591. var vertexIndex = indices[index];
  28592. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28593. kind = kinds[kindIndex];
  28594. var stride = vbs[kind].getStrideSize();
  28595. for (var offset = 0; offset < stride; offset++) {
  28596. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28597. }
  28598. }
  28599. }
  28600. // Updating indices
  28601. for (index = 0; index < totalIndices; index += 3) {
  28602. indices[index] = index;
  28603. indices[index + 1] = index + 1;
  28604. indices[index + 2] = index + 2;
  28605. }
  28606. this.setIndices(indices);
  28607. // Updating vertex buffers
  28608. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28609. kind = kinds[kindIndex];
  28610. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28611. }
  28612. // Updating submeshes
  28613. this.releaseSubMeshes();
  28614. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28615. var previousOne = previousSubmeshes[submeshIndex];
  28616. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28617. }
  28618. this._unIndexed = true;
  28619. this.synchronizeInstances();
  28620. return this;
  28621. };
  28622. /**
  28623. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28624. * This method returns the Mesh.
  28625. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28626. */
  28627. Mesh.prototype.flipFaces = function (flipNormals) {
  28628. if (flipNormals === void 0) { flipNormals = false; }
  28629. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28630. var i;
  28631. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28632. for (i = 0; i < vertex_data.normals.length; i++) {
  28633. vertex_data.normals[i] *= -1;
  28634. }
  28635. }
  28636. if (vertex_data.indices) {
  28637. var temp;
  28638. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28639. // reassign indices
  28640. temp = vertex_data.indices[i + 1];
  28641. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28642. vertex_data.indices[i + 2] = temp;
  28643. }
  28644. }
  28645. vertex_data.applyToMesh(this);
  28646. return this;
  28647. };
  28648. // Instances
  28649. /**
  28650. * Creates a new InstancedMesh object from the mesh model.
  28651. * An instance shares the same properties and the same material than its model.
  28652. * Only these properties of each instance can then be set individually :
  28653. * - position
  28654. * - rotation
  28655. * - rotationQuaternion
  28656. * - setPivotMatrix
  28657. * - scaling
  28658. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28659. * Warning : this method is not supported for Line mesh and LineSystem
  28660. */
  28661. Mesh.prototype.createInstance = function (name) {
  28662. return new BABYLON.InstancedMesh(name, this);
  28663. };
  28664. /**
  28665. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28666. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28667. * This method returns the Mesh.
  28668. */
  28669. Mesh.prototype.synchronizeInstances = function () {
  28670. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28671. var instance = this.instances[instanceIndex];
  28672. instance._syncSubMeshes();
  28673. }
  28674. return this;
  28675. };
  28676. /**
  28677. * Simplify the mesh according to the given array of settings.
  28678. * Function will return immediately and will simplify async. It returns the Mesh.
  28679. * @param settings a collection of simplification settings.
  28680. * @param parallelProcessing should all levels calculate parallel or one after the other.
  28681. * @param type the type of simplification to run.
  28682. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  28683. */
  28684. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  28685. if (parallelProcessing === void 0) { parallelProcessing = true; }
  28686. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  28687. this.getScene().simplificationQueue.addTask({
  28688. settings: settings,
  28689. parallelProcessing: parallelProcessing,
  28690. mesh: this,
  28691. simplificationType: simplificationType,
  28692. successCallback: successCallback
  28693. });
  28694. return this;
  28695. };
  28696. /**
  28697. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  28698. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  28699. * This should be used together with the simplification to avoid disappearing triangles.
  28700. * Returns the Mesh.
  28701. * @param successCallback an optional success callback to be called after the optimization finished.
  28702. */
  28703. Mesh.prototype.optimizeIndices = function (successCallback) {
  28704. var _this = this;
  28705. var indices = this.getIndices();
  28706. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28707. if (!positions || !indices) {
  28708. return this;
  28709. }
  28710. var vectorPositions = new Array();
  28711. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  28712. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  28713. }
  28714. var dupes = new Array();
  28715. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  28716. var realPos = vectorPositions.length - 1 - iteration;
  28717. var testedPosition = vectorPositions[realPos];
  28718. for (var j = 0; j < realPos; ++j) {
  28719. var againstPosition = vectorPositions[j];
  28720. if (testedPosition.equals(againstPosition)) {
  28721. dupes[realPos] = j;
  28722. break;
  28723. }
  28724. }
  28725. }, function () {
  28726. for (var i = 0; i < indices.length; ++i) {
  28727. indices[i] = dupes[indices[i]] || indices[i];
  28728. }
  28729. //indices are now reordered
  28730. var originalSubMeshes = _this.subMeshes.slice(0);
  28731. _this.setIndices(indices);
  28732. _this.subMeshes = originalSubMeshes;
  28733. if (successCallback) {
  28734. successCallback(_this);
  28735. }
  28736. });
  28737. return this;
  28738. };
  28739. Mesh.prototype.serialize = function (serializationObject) {
  28740. serializationObject.name = this.name;
  28741. serializationObject.id = this.id;
  28742. serializationObject.type = this.getClassName();
  28743. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28744. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28745. }
  28746. serializationObject.position = this.position.asArray();
  28747. if (this.rotationQuaternion) {
  28748. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  28749. }
  28750. else if (this.rotation) {
  28751. serializationObject.rotation = this.rotation.asArray();
  28752. }
  28753. serializationObject.scaling = this.scaling.asArray();
  28754. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  28755. serializationObject.isEnabled = this.isEnabled(false);
  28756. serializationObject.isVisible = this.isVisible;
  28757. serializationObject.infiniteDistance = this.infiniteDistance;
  28758. serializationObject.pickable = this.isPickable;
  28759. serializationObject.receiveShadows = this.receiveShadows;
  28760. serializationObject.billboardMode = this.billboardMode;
  28761. serializationObject.visibility = this.visibility;
  28762. serializationObject.checkCollisions = this.checkCollisions;
  28763. serializationObject.isBlocker = this.isBlocker;
  28764. // Parent
  28765. if (this.parent) {
  28766. serializationObject.parentId = this.parent.id;
  28767. }
  28768. // Geometry
  28769. serializationObject.isUnIndexed = this.isUnIndexed;
  28770. var geometry = this._geometry;
  28771. if (geometry) {
  28772. var geometryId = geometry.id;
  28773. serializationObject.geometryId = geometryId;
  28774. // SubMeshes
  28775. serializationObject.subMeshes = [];
  28776. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  28777. var subMesh = this.subMeshes[subIndex];
  28778. serializationObject.subMeshes.push({
  28779. materialIndex: subMesh.materialIndex,
  28780. verticesStart: subMesh.verticesStart,
  28781. verticesCount: subMesh.verticesCount,
  28782. indexStart: subMesh.indexStart,
  28783. indexCount: subMesh.indexCount
  28784. });
  28785. }
  28786. }
  28787. // Material
  28788. if (this.material) {
  28789. serializationObject.materialId = this.material.id;
  28790. }
  28791. else {
  28792. this.material = null;
  28793. }
  28794. // Morph targets
  28795. if (this.morphTargetManager) {
  28796. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  28797. }
  28798. // Skeleton
  28799. if (this.skeleton) {
  28800. serializationObject.skeletonId = this.skeleton.id;
  28801. }
  28802. // Physics
  28803. //TODO implement correct serialization for physics impostors.
  28804. var impostor = this.getPhysicsImpostor();
  28805. if (impostor) {
  28806. serializationObject.physicsMass = impostor.getParam("mass");
  28807. serializationObject.physicsFriction = impostor.getParam("friction");
  28808. serializationObject.physicsRestitution = impostor.getParam("mass");
  28809. serializationObject.physicsImpostor = impostor.type;
  28810. }
  28811. // Metadata
  28812. if (this.metadata) {
  28813. serializationObject.metadata = this.metadata;
  28814. }
  28815. // Instances
  28816. serializationObject.instances = [];
  28817. for (var index = 0; index < this.instances.length; index++) {
  28818. var instance = this.instances[index];
  28819. var serializationInstance = {
  28820. name: instance.name,
  28821. id: instance.id,
  28822. position: instance.position.asArray(),
  28823. scaling: instance.scaling.asArray()
  28824. };
  28825. if (instance.rotationQuaternion) {
  28826. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  28827. }
  28828. else if (instance.rotation) {
  28829. serializationInstance.rotation = instance.rotation.asArray();
  28830. }
  28831. serializationObject.instances.push(serializationInstance);
  28832. // Animations
  28833. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  28834. serializationInstance.ranges = instance.serializeAnimationRanges();
  28835. }
  28836. //
  28837. // Animations
  28838. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28839. serializationObject.ranges = this.serializeAnimationRanges();
  28840. // Layer mask
  28841. serializationObject.layerMask = this.layerMask;
  28842. // Alpha
  28843. serializationObject.alphaIndex = this.alphaIndex;
  28844. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  28845. // Overlay
  28846. serializationObject.overlayAlpha = this.overlayAlpha;
  28847. serializationObject.overlayColor = this.overlayColor.asArray();
  28848. serializationObject.renderOverlay = this.renderOverlay;
  28849. // Fog
  28850. serializationObject.applyFog = this.applyFog;
  28851. // Action Manager
  28852. if (this.actionManager) {
  28853. serializationObject.actions = this.actionManager.serialize(this.name);
  28854. }
  28855. };
  28856. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  28857. if (!this.geometry) {
  28858. return;
  28859. }
  28860. this._markSubMeshesAsAttributesDirty();
  28861. var morphTargetManager = this._morphTargetManager;
  28862. if (morphTargetManager && morphTargetManager.vertexCount) {
  28863. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  28864. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  28865. this.morphTargetManager = null;
  28866. return;
  28867. }
  28868. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  28869. var morphTarget = morphTargetManager.getActiveTarget(index);
  28870. var positions = morphTarget.getPositions();
  28871. if (!positions) {
  28872. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  28873. return;
  28874. }
  28875. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  28876. var normals = morphTarget.getNormals();
  28877. if (normals) {
  28878. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  28879. }
  28880. var tangents = morphTarget.getTangents();
  28881. if (tangents) {
  28882. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  28883. }
  28884. }
  28885. }
  28886. else {
  28887. var index = 0;
  28888. // Positions
  28889. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  28890. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  28891. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  28892. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  28893. }
  28894. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  28895. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  28896. }
  28897. index++;
  28898. }
  28899. }
  28900. };
  28901. // Statics
  28902. /**
  28903. * Returns a new Mesh object parsed from the source provided.
  28904. * The parameter `parsedMesh` is the source.
  28905. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  28906. */
  28907. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  28908. var mesh;
  28909. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  28910. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  28911. }
  28912. else {
  28913. mesh = new Mesh(parsedMesh.name, scene);
  28914. }
  28915. mesh.id = parsedMesh.id;
  28916. if (BABYLON.Tags) {
  28917. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  28918. }
  28919. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  28920. if (parsedMesh.metadata !== undefined) {
  28921. mesh.metadata = parsedMesh.metadata;
  28922. }
  28923. if (parsedMesh.rotationQuaternion) {
  28924. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  28925. }
  28926. else if (parsedMesh.rotation) {
  28927. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  28928. }
  28929. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  28930. if (parsedMesh.localMatrix) {
  28931. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  28932. }
  28933. else if (parsedMesh.pivotMatrix) {
  28934. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  28935. }
  28936. mesh.setEnabled(parsedMesh.isEnabled);
  28937. mesh.isVisible = parsedMesh.isVisible;
  28938. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  28939. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  28940. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  28941. if (parsedMesh.applyFog !== undefined) {
  28942. mesh.applyFog = parsedMesh.applyFog;
  28943. }
  28944. if (parsedMesh.pickable !== undefined) {
  28945. mesh.isPickable = parsedMesh.pickable;
  28946. }
  28947. if (parsedMesh.alphaIndex !== undefined) {
  28948. mesh.alphaIndex = parsedMesh.alphaIndex;
  28949. }
  28950. mesh.receiveShadows = parsedMesh.receiveShadows;
  28951. mesh.billboardMode = parsedMesh.billboardMode;
  28952. if (parsedMesh.visibility !== undefined) {
  28953. mesh.visibility = parsedMesh.visibility;
  28954. }
  28955. mesh.checkCollisions = parsedMesh.checkCollisions;
  28956. if (parsedMesh.isBlocker !== undefined) {
  28957. mesh.isBlocker = parsedMesh.isBlocker;
  28958. }
  28959. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  28960. // freezeWorldMatrix
  28961. if (parsedMesh.freezeWorldMatrix) {
  28962. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  28963. }
  28964. // Parent
  28965. if (parsedMesh.parentId) {
  28966. mesh._waitingParentId = parsedMesh.parentId;
  28967. }
  28968. // Actions
  28969. if (parsedMesh.actions !== undefined) {
  28970. mesh._waitingActions = parsedMesh.actions;
  28971. }
  28972. // Overlay
  28973. if (parsedMesh.overlayAlpha !== undefined) {
  28974. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  28975. }
  28976. if (parsedMesh.overlayColor !== undefined) {
  28977. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  28978. }
  28979. if (parsedMesh.renderOverlay !== undefined) {
  28980. mesh.renderOverlay = parsedMesh.renderOverlay;
  28981. }
  28982. // Geometry
  28983. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  28984. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  28985. if (parsedMesh.delayLoadingFile) {
  28986. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28987. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  28988. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  28989. if (parsedMesh._binaryInfo) {
  28990. mesh._binaryInfo = parsedMesh._binaryInfo;
  28991. }
  28992. mesh._delayInfo = [];
  28993. if (parsedMesh.hasUVs) {
  28994. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28995. }
  28996. if (parsedMesh.hasUVs2) {
  28997. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28998. }
  28999. if (parsedMesh.hasUVs3) {
  29000. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29001. }
  29002. if (parsedMesh.hasUVs4) {
  29003. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29004. }
  29005. if (parsedMesh.hasUVs5) {
  29006. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29007. }
  29008. if (parsedMesh.hasUVs6) {
  29009. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29010. }
  29011. if (parsedMesh.hasColors) {
  29012. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29013. }
  29014. if (parsedMesh.hasMatricesIndices) {
  29015. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29016. }
  29017. if (parsedMesh.hasMatricesWeights) {
  29018. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29019. }
  29020. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29021. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29022. mesh._checkDelayState();
  29023. }
  29024. }
  29025. else {
  29026. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29027. }
  29028. // Material
  29029. if (parsedMesh.materialId) {
  29030. mesh.setMaterialByID(parsedMesh.materialId);
  29031. }
  29032. else {
  29033. mesh.material = null;
  29034. }
  29035. // Morph targets
  29036. if (parsedMesh.morphTargetManagerId > -1) {
  29037. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29038. }
  29039. // Skeleton
  29040. if (parsedMesh.skeletonId > -1) {
  29041. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29042. if (parsedMesh.numBoneInfluencers) {
  29043. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29044. }
  29045. }
  29046. // Animations
  29047. if (parsedMesh.animations) {
  29048. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29049. var parsedAnimation = parsedMesh.animations[animationIndex];
  29050. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29051. }
  29052. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29053. }
  29054. if (parsedMesh.autoAnimate) {
  29055. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29056. }
  29057. // Layer Mask
  29058. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29059. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29060. }
  29061. else {
  29062. mesh.layerMask = 0x0FFFFFFF;
  29063. }
  29064. // Physics
  29065. if (parsedMesh.physicsImpostor) {
  29066. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29067. mass: parsedMesh.physicsMass,
  29068. friction: parsedMesh.physicsFriction,
  29069. restitution: parsedMesh.physicsRestitution
  29070. }, scene);
  29071. }
  29072. // Instances
  29073. if (parsedMesh.instances) {
  29074. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29075. var parsedInstance = parsedMesh.instances[index];
  29076. var instance = mesh.createInstance(parsedInstance.name);
  29077. if (parsedInstance.id) {
  29078. instance.id = parsedInstance.id;
  29079. }
  29080. if (BABYLON.Tags) {
  29081. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29082. }
  29083. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29084. if (parsedInstance.parentId) {
  29085. instance._waitingParentId = parsedInstance.parentId;
  29086. }
  29087. if (parsedInstance.rotationQuaternion) {
  29088. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29089. }
  29090. else if (parsedInstance.rotation) {
  29091. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29092. }
  29093. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29094. instance.checkCollisions = mesh.checkCollisions;
  29095. if (parsedMesh.animations) {
  29096. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29097. parsedAnimation = parsedMesh.animations[animationIndex];
  29098. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29099. }
  29100. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29101. }
  29102. }
  29103. }
  29104. return mesh;
  29105. };
  29106. /**
  29107. * Creates a ribbon mesh.
  29108. * Please consider using the same method from the MeshBuilder class instead.
  29109. * 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.
  29110. *
  29111. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29112. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29113. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29114. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29115. * 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.
  29116. * 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.
  29117. * 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
  29118. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29119. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29120. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29121. */
  29122. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29123. if (closeArray === void 0) { closeArray = false; }
  29124. if (updatable === void 0) { updatable = false; }
  29125. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29126. pathArray: pathArray,
  29127. closeArray: closeArray,
  29128. closePath: closePath,
  29129. offset: offset,
  29130. updatable: updatable,
  29131. sideOrientation: sideOrientation,
  29132. instance: instance
  29133. }, scene);
  29134. };
  29135. /**
  29136. * Creates a plane polygonal mesh. By default, this is a disc.
  29137. * Please consider using the same method from the MeshBuilder class instead.
  29138. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29139. * 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.
  29140. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29141. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29142. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29143. */
  29144. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29145. if (scene === void 0) { scene = null; }
  29146. var options = {
  29147. radius: radius,
  29148. tessellation: tessellation,
  29149. sideOrientation: sideOrientation,
  29150. updatable: updatable
  29151. };
  29152. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29153. };
  29154. /**
  29155. * Creates a box mesh.
  29156. * Please consider using the same method from the MeshBuilder class instead.
  29157. * The parameter `size` sets the size (float) of each box side (default 1).
  29158. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29159. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29160. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29161. */
  29162. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29163. if (scene === void 0) { scene = null; }
  29164. var options = {
  29165. size: size,
  29166. sideOrientation: sideOrientation,
  29167. updatable: updatable
  29168. };
  29169. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29170. };
  29171. /**
  29172. * Creates a sphere mesh.
  29173. * Please consider using the same method from the MeshBuilder class instead.
  29174. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29175. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29176. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29177. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29178. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29179. */
  29180. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29181. var options = {
  29182. segments: segments,
  29183. diameterX: diameter,
  29184. diameterY: diameter,
  29185. diameterZ: diameter,
  29186. sideOrientation: sideOrientation,
  29187. updatable: updatable
  29188. };
  29189. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29190. };
  29191. /**
  29192. * Creates a cylinder or a cone mesh.
  29193. * Please consider using the same method from the MeshBuilder class instead.
  29194. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29195. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29196. * 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.
  29197. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29198. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29199. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29200. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29201. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29202. */
  29203. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29204. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29205. if (scene !== undefined) {
  29206. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29207. updatable = scene;
  29208. }
  29209. scene = subdivisions;
  29210. subdivisions = 1;
  29211. }
  29212. var options = {
  29213. height: height,
  29214. diameterTop: diameterTop,
  29215. diameterBottom: diameterBottom,
  29216. tessellation: tessellation,
  29217. subdivisions: subdivisions,
  29218. sideOrientation: sideOrientation,
  29219. updatable: updatable
  29220. };
  29221. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29222. };
  29223. // Torus (Code from SharpDX.org)
  29224. /**
  29225. * Creates a torus mesh.
  29226. * Please consider using the same method from the MeshBuilder class instead.
  29227. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29228. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29229. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29230. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29231. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29232. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29233. */
  29234. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29235. var options = {
  29236. diameter: diameter,
  29237. thickness: thickness,
  29238. tessellation: tessellation,
  29239. sideOrientation: sideOrientation,
  29240. updatable: updatable
  29241. };
  29242. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29243. };
  29244. /**
  29245. * Creates a torus knot mesh.
  29246. * Please consider using the same method from the MeshBuilder class instead.
  29247. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29248. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29249. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29250. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29251. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29252. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29253. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29254. */
  29255. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29256. var options = {
  29257. radius: radius,
  29258. tube: tube,
  29259. radialSegments: radialSegments,
  29260. tubularSegments: tubularSegments,
  29261. p: p,
  29262. q: q,
  29263. sideOrientation: sideOrientation,
  29264. updatable: updatable
  29265. };
  29266. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29267. };
  29268. /**
  29269. * Creates a line mesh.
  29270. * Please consider using the same method from the MeshBuilder class instead.
  29271. * 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.
  29272. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29273. * The parameter `points` is an array successive Vector3.
  29274. * 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
  29275. * When updating an instance, remember that only point positions can change, not the number of points.
  29276. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29277. */
  29278. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29279. if (scene === void 0) { scene = null; }
  29280. if (updatable === void 0) { updatable = false; }
  29281. if (instance === void 0) { instance = null; }
  29282. var options = {
  29283. points: points,
  29284. updatable: updatable,
  29285. instance: instance
  29286. };
  29287. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29288. };
  29289. /**
  29290. * Creates a dashed line mesh.
  29291. * Please consider using the same method from the MeshBuilder class instead.
  29292. * 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.
  29293. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29294. * The parameter `points` is an array successive Vector3.
  29295. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29296. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29297. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29298. * 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
  29299. * When updating an instance, remember that only point positions can change, not the number of points.
  29300. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29301. */
  29302. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29303. if (scene === void 0) { scene = null; }
  29304. var options = {
  29305. points: points,
  29306. dashSize: dashSize,
  29307. gapSize: gapSize,
  29308. dashNb: dashNb,
  29309. updatable: updatable,
  29310. instance: instance
  29311. };
  29312. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29313. };
  29314. /**
  29315. * Creates a polygon mesh.
  29316. * Please consider using the same method from the MeshBuilder class instead.
  29317. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29318. * 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.
  29319. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29321. * Remember you can only change the shape positions, not their number when updating a polygon.
  29322. */
  29323. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29324. var options = {
  29325. shape: shape,
  29326. holes: holes,
  29327. updatable: updatable,
  29328. sideOrientation: sideOrientation
  29329. };
  29330. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29331. };
  29332. /**
  29333. * Creates an extruded polygon mesh, with depth in the Y direction.
  29334. * Please consider using the same method from the MeshBuilder class instead.
  29335. */
  29336. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29337. var options = {
  29338. shape: shape,
  29339. holes: holes,
  29340. depth: depth,
  29341. updatable: updatable,
  29342. sideOrientation: sideOrientation
  29343. };
  29344. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29345. };
  29346. /**
  29347. * Creates an extruded shape mesh.
  29348. * 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.
  29349. * Please consider using the same method from the MeshBuilder class instead.
  29350. *
  29351. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29352. * 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
  29353. * extruded along the Z axis.
  29354. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29355. * 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.
  29356. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29357. * 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
  29358. * 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
  29359. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29360. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29361. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29362. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29363. */
  29364. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29365. if (scene === void 0) { scene = null; }
  29366. var options = {
  29367. shape: shape,
  29368. path: path,
  29369. scale: scale,
  29370. rotation: rotation,
  29371. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29372. sideOrientation: sideOrientation,
  29373. instance: instance,
  29374. updatable: updatable
  29375. };
  29376. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29377. };
  29378. /**
  29379. * Creates an custom extruded shape mesh.
  29380. * 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.
  29381. * Please consider using the same method from the MeshBuilder class instead.
  29382. *
  29383. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29384. * 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
  29385. * extruded along the Z axis.
  29386. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29387. * 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
  29388. * and the distance of this point from the begining of the path :
  29389. * ```javascript
  29390. * var rotationFunction = function(i, distance) {
  29391. * // do things
  29392. * return rotationValue; }
  29393. * ```
  29394. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29395. * 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
  29396. * and the distance of this point from the begining of the path :
  29397. * ```javascript
  29398. * var scaleFunction = function(i, distance) {
  29399. * // do things
  29400. * return scaleValue;}
  29401. * ```
  29402. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29403. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29404. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29405. * 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
  29406. * 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
  29407. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29408. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29409. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29411. */
  29412. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29413. var options = {
  29414. shape: shape,
  29415. path: path,
  29416. scaleFunction: scaleFunction,
  29417. rotationFunction: rotationFunction,
  29418. ribbonCloseArray: ribbonCloseArray,
  29419. ribbonClosePath: ribbonClosePath,
  29420. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29421. sideOrientation: sideOrientation,
  29422. instance: instance,
  29423. updatable: updatable
  29424. };
  29425. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29426. };
  29427. /**
  29428. * Creates lathe mesh.
  29429. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29430. * Please consider using the same method from the MeshBuilder class instead.
  29431. * 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
  29432. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29433. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29434. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29435. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29436. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29437. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29438. */
  29439. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29440. var options = {
  29441. shape: shape,
  29442. radius: radius,
  29443. tessellation: tessellation,
  29444. sideOrientation: sideOrientation,
  29445. updatable: updatable
  29446. };
  29447. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29448. };
  29449. /**
  29450. * Creates a plane mesh.
  29451. * Please consider using the same method from the MeshBuilder class instead.
  29452. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29453. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29454. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29455. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29456. */
  29457. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29458. var options = {
  29459. size: size,
  29460. width: size,
  29461. height: size,
  29462. sideOrientation: sideOrientation,
  29463. updatable: updatable
  29464. };
  29465. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29466. };
  29467. /**
  29468. * Creates a ground mesh.
  29469. * Please consider using the same method from the MeshBuilder class instead.
  29470. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29471. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29472. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29473. */
  29474. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29475. var options = {
  29476. width: width,
  29477. height: height,
  29478. subdivisions: subdivisions,
  29479. updatable: updatable
  29480. };
  29481. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29482. };
  29483. /**
  29484. * Creates a tiled ground mesh.
  29485. * Please consider using the same method from the MeshBuilder class instead.
  29486. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29487. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29488. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29489. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29490. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29491. * numbers of subdivisions on the ground width and height of each tile.
  29492. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29493. */
  29494. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29495. var options = {
  29496. xmin: xmin,
  29497. zmin: zmin,
  29498. xmax: xmax,
  29499. zmax: zmax,
  29500. subdivisions: subdivisions,
  29501. precision: precision,
  29502. updatable: updatable
  29503. };
  29504. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29505. };
  29506. /**
  29507. * Creates a ground mesh from a height map.
  29508. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29509. * Please consider using the same method from the MeshBuilder class instead.
  29510. * The parameter `url` sets the URL of the height map image resource.
  29511. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29512. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29513. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29514. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29515. * 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).
  29516. * This function is passed the newly built mesh :
  29517. * ```javascript
  29518. * function(mesh) { // do things
  29519. * return; }
  29520. * ```
  29521. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29522. */
  29523. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29524. var options = {
  29525. width: width,
  29526. height: height,
  29527. subdivisions: subdivisions,
  29528. minHeight: minHeight,
  29529. maxHeight: maxHeight,
  29530. updatable: updatable,
  29531. onReady: onReady
  29532. };
  29533. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29534. };
  29535. /**
  29536. * Creates a tube mesh.
  29537. * 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.
  29538. * Please consider using the same method from the MeshBuilder class instead.
  29539. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29540. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29541. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29542. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29543. * 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.
  29544. * It must return a radius value (positive float) :
  29545. * ```javascript
  29546. * var radiusFunction = function(i, distance) {
  29547. * // do things
  29548. * return radius; }
  29549. * ```
  29550. * 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
  29551. * 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
  29552. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29553. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29554. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29555. */
  29556. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29557. var options = {
  29558. path: path,
  29559. radius: radius,
  29560. tessellation: tessellation,
  29561. radiusFunction: radiusFunction,
  29562. arc: 1,
  29563. cap: cap,
  29564. updatable: updatable,
  29565. sideOrientation: sideOrientation,
  29566. instance: instance
  29567. };
  29568. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29569. };
  29570. /**
  29571. * Creates a polyhedron mesh.
  29572. * Please consider using the same method from the MeshBuilder class instead.
  29573. * 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
  29574. * to choose the wanted type.
  29575. * The parameter `size` (positive float, default 1) sets the polygon size.
  29576. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29577. * 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`.
  29578. * 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
  29579. * 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)`).
  29580. * 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
  29581. * 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.
  29582. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29583. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29584. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29585. */
  29586. Mesh.CreatePolyhedron = function (name, options, scene) {
  29587. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29588. };
  29589. /**
  29590. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29591. * Please consider using the same method from the MeshBuilder class instead.
  29592. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29593. * 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`).
  29594. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29595. * 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.
  29596. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29597. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29598. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29599. */
  29600. Mesh.CreateIcoSphere = function (name, options, scene) {
  29601. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29602. };
  29603. /**
  29604. * Creates a decal mesh.
  29605. * Please consider using the same method from the MeshBuilder class instead.
  29606. * 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.
  29607. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29608. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29609. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29610. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29611. */
  29612. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29613. var options = {
  29614. position: position,
  29615. normal: normal,
  29616. size: size,
  29617. angle: angle
  29618. };
  29619. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29620. };
  29621. // Skeletons
  29622. /**
  29623. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29624. */
  29625. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29626. if (!this._sourcePositions) {
  29627. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29628. if (!source) {
  29629. return this._sourcePositions;
  29630. }
  29631. this._sourcePositions = new Float32Array(source);
  29632. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29633. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29634. }
  29635. }
  29636. return this._sourcePositions;
  29637. };
  29638. /**
  29639. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29640. */
  29641. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29642. if (!this._sourceNormals) {
  29643. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29644. if (!source) {
  29645. return this._sourceNormals;
  29646. }
  29647. this._sourceNormals = new Float32Array(source);
  29648. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29649. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29650. }
  29651. }
  29652. return this._sourceNormals;
  29653. };
  29654. /**
  29655. * Updates the vertex buffer by applying transformation from the bones.
  29656. * Returns the Mesh.
  29657. *
  29658. * @param {skeleton} skeleton to apply
  29659. */
  29660. Mesh.prototype.applySkeleton = function (skeleton) {
  29661. if (!this.geometry) {
  29662. return this;
  29663. }
  29664. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29665. return this;
  29666. }
  29667. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29668. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29669. return this;
  29670. }
  29671. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29672. return this;
  29673. }
  29674. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29675. return this;
  29676. }
  29677. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29678. return this;
  29679. }
  29680. if (!this._sourcePositions) {
  29681. var submeshes = this.subMeshes.slice();
  29682. this.setPositionsForCPUSkinning();
  29683. this.subMeshes = submeshes;
  29684. }
  29685. if (!this._sourceNormals) {
  29686. this.setNormalsForCPUSkinning();
  29687. }
  29688. // positionsData checks for not being Float32Array will only pass at most once
  29689. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29690. if (!positionsData) {
  29691. return this;
  29692. }
  29693. if (!(positionsData instanceof Float32Array)) {
  29694. positionsData = new Float32Array(positionsData);
  29695. }
  29696. // normalsData checks for not being Float32Array will only pass at most once
  29697. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29698. if (!normalsData) {
  29699. return this;
  29700. }
  29701. if (!(normalsData instanceof Float32Array)) {
  29702. normalsData = new Float32Array(normalsData);
  29703. }
  29704. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29705. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29706. if (!matricesWeightsData || !matricesIndicesData) {
  29707. return this;
  29708. }
  29709. var needExtras = this.numBoneInfluencers > 4;
  29710. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29711. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29712. var skeletonMatrices = skeleton.getTransformMatrices(this);
  29713. var tempVector3 = BABYLON.Vector3.Zero();
  29714. var finalMatrix = new BABYLON.Matrix();
  29715. var tempMatrix = new BABYLON.Matrix();
  29716. var matWeightIdx = 0;
  29717. var inf;
  29718. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  29719. var weight;
  29720. for (inf = 0; inf < 4; inf++) {
  29721. weight = matricesWeightsData[matWeightIdx + inf];
  29722. if (weight > 0) {
  29723. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  29724. finalMatrix.addToSelf(tempMatrix);
  29725. }
  29726. else
  29727. break;
  29728. }
  29729. if (needExtras) {
  29730. for (inf = 0; inf < 4; inf++) {
  29731. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29732. if (weight > 0) {
  29733. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  29734. finalMatrix.addToSelf(tempMatrix);
  29735. }
  29736. else
  29737. break;
  29738. }
  29739. }
  29740. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  29741. tempVector3.toArray(positionsData, index);
  29742. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  29743. tempVector3.toArray(normalsData, index);
  29744. finalMatrix.reset();
  29745. }
  29746. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  29747. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  29748. return this;
  29749. };
  29750. // Tools
  29751. /**
  29752. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  29753. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  29754. */
  29755. Mesh.MinMax = function (meshes) {
  29756. var minVector = null;
  29757. var maxVector = null;
  29758. meshes.forEach(function (mesh, index, array) {
  29759. var boundingInfo = mesh.getBoundingInfo();
  29760. var boundingBox = boundingInfo.boundingBox;
  29761. if (!minVector || !maxVector) {
  29762. minVector = boundingBox.minimumWorld;
  29763. maxVector = boundingBox.maximumWorld;
  29764. }
  29765. else {
  29766. minVector.minimizeInPlace(boundingBox.minimumWorld);
  29767. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  29768. }
  29769. });
  29770. if (!minVector || !maxVector) {
  29771. return {
  29772. min: BABYLON.Vector3.Zero(),
  29773. max: BABYLON.Vector3.Zero()
  29774. };
  29775. }
  29776. return {
  29777. min: minVector,
  29778. max: maxVector
  29779. };
  29780. };
  29781. /**
  29782. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  29783. */
  29784. Mesh.Center = function (meshesOrMinMaxVector) {
  29785. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  29786. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  29787. };
  29788. /**
  29789. * Merge the array of meshes into a single mesh for performance reasons.
  29790. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  29791. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  29792. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  29793. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  29794. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  29795. */
  29796. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  29797. if (disposeSource === void 0) { disposeSource = true; }
  29798. var index;
  29799. if (!allow32BitsIndices) {
  29800. var totalVertices = 0;
  29801. // Counting vertices
  29802. for (index = 0; index < meshes.length; index++) {
  29803. if (meshes[index]) {
  29804. totalVertices += meshes[index].getTotalVertices();
  29805. if (totalVertices > 65536) {
  29806. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  29807. return null;
  29808. }
  29809. }
  29810. }
  29811. }
  29812. // Merge
  29813. var vertexData = null;
  29814. var otherVertexData;
  29815. var indiceArray = new Array();
  29816. var source = null;
  29817. for (index = 0; index < meshes.length; index++) {
  29818. if (meshes[index]) {
  29819. meshes[index].computeWorldMatrix(true);
  29820. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  29821. otherVertexData.transform(meshes[index].getWorldMatrix());
  29822. if (vertexData) {
  29823. vertexData.merge(otherVertexData);
  29824. }
  29825. else {
  29826. vertexData = otherVertexData;
  29827. source = meshes[index];
  29828. }
  29829. if (subdivideWithSubMeshes) {
  29830. indiceArray.push(meshes[index].getTotalIndices());
  29831. }
  29832. }
  29833. }
  29834. source = source;
  29835. if (!meshSubclass) {
  29836. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  29837. }
  29838. vertexData.applyToMesh(meshSubclass);
  29839. // Setting properties
  29840. meshSubclass.material = source.material;
  29841. meshSubclass.checkCollisions = source.checkCollisions;
  29842. // Cleaning
  29843. if (disposeSource) {
  29844. for (index = 0; index < meshes.length; index++) {
  29845. if (meshes[index]) {
  29846. meshes[index].dispose();
  29847. }
  29848. }
  29849. }
  29850. // Subdivide
  29851. if (subdivideWithSubMeshes) {
  29852. //-- Suppresions du submesh global
  29853. meshSubclass.releaseSubMeshes();
  29854. index = 0;
  29855. var offset = 0;
  29856. //-- aplique la subdivision en fonction du tableau d'indices
  29857. while (index < indiceArray.length) {
  29858. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  29859. offset += indiceArray[index];
  29860. index++;
  29861. }
  29862. }
  29863. return meshSubclass;
  29864. };
  29865. // Consts
  29866. Mesh._FRONTSIDE = 0;
  29867. Mesh._BACKSIDE = 1;
  29868. Mesh._DOUBLESIDE = 2;
  29869. Mesh._DEFAULTSIDE = 0;
  29870. Mesh._NO_CAP = 0;
  29871. Mesh._CAP_START = 1;
  29872. Mesh._CAP_END = 2;
  29873. Mesh._CAP_ALL = 3;
  29874. return Mesh;
  29875. }(BABYLON.AbstractMesh));
  29876. BABYLON.Mesh = Mesh;
  29877. })(BABYLON || (BABYLON = {}));
  29878. //# sourceMappingURL=babylon.mesh.js.map
  29879. var BABYLON;
  29880. (function (BABYLON) {
  29881. var BaseSubMesh = /** @class */ (function () {
  29882. function BaseSubMesh() {
  29883. }
  29884. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  29885. get: function () {
  29886. return this._materialEffect;
  29887. },
  29888. enumerable: true,
  29889. configurable: true
  29890. });
  29891. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  29892. if (defines === void 0) { defines = null; }
  29893. if (this._materialEffect === effect) {
  29894. if (!effect) {
  29895. this._materialDefines = null;
  29896. }
  29897. return;
  29898. }
  29899. this._materialDefines = defines;
  29900. this._materialEffect = effect;
  29901. };
  29902. return BaseSubMesh;
  29903. }());
  29904. BABYLON.BaseSubMesh = BaseSubMesh;
  29905. var SubMesh = /** @class */ (function (_super) {
  29906. __extends(SubMesh, _super);
  29907. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29908. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29909. var _this = _super.call(this) || this;
  29910. _this.materialIndex = materialIndex;
  29911. _this.verticesStart = verticesStart;
  29912. _this.verticesCount = verticesCount;
  29913. _this.indexStart = indexStart;
  29914. _this.indexCount = indexCount;
  29915. _this._renderId = 0;
  29916. _this._mesh = mesh;
  29917. _this._renderingMesh = renderingMesh || mesh;
  29918. mesh.subMeshes.push(_this);
  29919. _this._trianglePlanes = [];
  29920. _this._id = mesh.subMeshes.length - 1;
  29921. if (createBoundingBox) {
  29922. _this.refreshBoundingInfo();
  29923. mesh.computeWorldMatrix(true);
  29924. }
  29925. return _this;
  29926. }
  29927. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29928. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29929. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  29930. };
  29931. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  29932. get: function () {
  29933. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  29934. },
  29935. enumerable: true,
  29936. configurable: true
  29937. });
  29938. /**
  29939. * Returns the submesh BoudingInfo object.
  29940. */
  29941. SubMesh.prototype.getBoundingInfo = function () {
  29942. if (this.IsGlobal) {
  29943. return this._mesh.getBoundingInfo();
  29944. }
  29945. return this._boundingInfo;
  29946. };
  29947. /**
  29948. * Sets the submesh BoundingInfo.
  29949. * Return the SubMesh.
  29950. */
  29951. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  29952. this._boundingInfo = boundingInfo;
  29953. return this;
  29954. };
  29955. /**
  29956. * Returns the mesh of the current submesh.
  29957. */
  29958. SubMesh.prototype.getMesh = function () {
  29959. return this._mesh;
  29960. };
  29961. /**
  29962. * Returns the rendering mesh of the submesh.
  29963. */
  29964. SubMesh.prototype.getRenderingMesh = function () {
  29965. return this._renderingMesh;
  29966. };
  29967. /**
  29968. * Returns the submesh material.
  29969. */
  29970. SubMesh.prototype.getMaterial = function () {
  29971. var rootMaterial = this._renderingMesh.material;
  29972. if (rootMaterial === null || rootMaterial === undefined) {
  29973. return this._mesh.getScene().defaultMaterial;
  29974. }
  29975. else if (rootMaterial.getSubMaterial) {
  29976. var multiMaterial = rootMaterial;
  29977. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  29978. if (this._currentMaterial !== effectiveMaterial) {
  29979. this._currentMaterial = effectiveMaterial;
  29980. this._materialDefines = null;
  29981. }
  29982. return effectiveMaterial;
  29983. }
  29984. return rootMaterial;
  29985. };
  29986. // Methods
  29987. /**
  29988. * Sets a new updated BoundingInfo object to the submesh.
  29989. * Returns the SubMesh.
  29990. */
  29991. SubMesh.prototype.refreshBoundingInfo = function () {
  29992. this._lastColliderWorldVertices = null;
  29993. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  29994. return this;
  29995. }
  29996. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29997. if (!data) {
  29998. this._boundingInfo = this._mesh.getBoundingInfo();
  29999. return this;
  30000. }
  30001. var indices = this._renderingMesh.getIndices();
  30002. var extend;
  30003. //is this the only submesh?
  30004. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30005. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30006. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30007. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30008. }
  30009. else {
  30010. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30011. }
  30012. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30013. return this;
  30014. };
  30015. SubMesh.prototype._checkCollision = function (collider) {
  30016. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30017. return boundingInfo._checkCollision(collider);
  30018. };
  30019. /**
  30020. * Updates the submesh BoundingInfo.
  30021. * Returns the Submesh.
  30022. */
  30023. SubMesh.prototype.updateBoundingInfo = function (world) {
  30024. var boundingInfo = this.getBoundingInfo();
  30025. if (!boundingInfo) {
  30026. this.refreshBoundingInfo();
  30027. boundingInfo = this.getBoundingInfo();
  30028. }
  30029. boundingInfo.update(world);
  30030. return this;
  30031. };
  30032. /**
  30033. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30034. * Boolean returned.
  30035. */
  30036. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30037. var boundingInfo = this.getBoundingInfo();
  30038. if (!boundingInfo) {
  30039. return false;
  30040. }
  30041. return boundingInfo.isInFrustum(frustumPlanes);
  30042. };
  30043. /**
  30044. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30045. * Boolean returned.
  30046. */
  30047. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30048. var boundingInfo = this.getBoundingInfo();
  30049. if (!boundingInfo) {
  30050. return false;
  30051. }
  30052. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30053. };
  30054. /**
  30055. * Renders the submesh.
  30056. * Returns it.
  30057. */
  30058. SubMesh.prototype.render = function (enableAlphaMode) {
  30059. this._renderingMesh.render(this, enableAlphaMode);
  30060. return this;
  30061. };
  30062. /**
  30063. * Returns a new Index Buffer.
  30064. * Type returned : WebGLBuffer.
  30065. */
  30066. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30067. if (!this._linesIndexBuffer) {
  30068. var linesIndices = [];
  30069. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30070. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30071. }
  30072. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30073. this.linesIndexCount = linesIndices.length;
  30074. }
  30075. return this._linesIndexBuffer;
  30076. };
  30077. /**
  30078. * True is the passed Ray intersects the submesh bounding box.
  30079. * Boolean returned.
  30080. */
  30081. SubMesh.prototype.canIntersects = function (ray) {
  30082. var boundingInfo = this.getBoundingInfo();
  30083. if (!boundingInfo) {
  30084. return false;
  30085. }
  30086. return ray.intersectsBox(boundingInfo.boundingBox);
  30087. };
  30088. /**
  30089. * Returns an object IntersectionInfo.
  30090. */
  30091. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30092. var intersectInfo = null;
  30093. // LineMesh first as it's also a Mesh...
  30094. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30095. var lineMesh = this._mesh;
  30096. // Line test
  30097. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30098. var p0 = positions[indices[index]];
  30099. var p1 = positions[indices[index + 1]];
  30100. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30101. if (length < 0) {
  30102. continue;
  30103. }
  30104. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30105. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30106. if (fastCheck) {
  30107. break;
  30108. }
  30109. }
  30110. }
  30111. }
  30112. else {
  30113. // Triangles test
  30114. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30115. var p0 = positions[indices[index]];
  30116. var p1 = positions[indices[index + 1]];
  30117. var p2 = positions[indices[index + 2]];
  30118. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30119. if (currentIntersectInfo) {
  30120. if (currentIntersectInfo.distance < 0) {
  30121. continue;
  30122. }
  30123. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30124. intersectInfo = currentIntersectInfo;
  30125. intersectInfo.faceId = index / 3;
  30126. if (fastCheck) {
  30127. break;
  30128. }
  30129. }
  30130. }
  30131. }
  30132. }
  30133. return intersectInfo;
  30134. };
  30135. SubMesh.prototype._rebuild = function () {
  30136. if (this._linesIndexBuffer) {
  30137. this._linesIndexBuffer = null;
  30138. }
  30139. };
  30140. // Clone
  30141. /**
  30142. * Creates a new Submesh from the passed Mesh.
  30143. */
  30144. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30145. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30146. if (!this.IsGlobal) {
  30147. var boundingInfo = this.getBoundingInfo();
  30148. if (!boundingInfo) {
  30149. return result;
  30150. }
  30151. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30152. }
  30153. return result;
  30154. };
  30155. // Dispose
  30156. /**
  30157. * Disposes the Submesh.
  30158. * Returns nothing.
  30159. */
  30160. SubMesh.prototype.dispose = function () {
  30161. if (this._linesIndexBuffer) {
  30162. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30163. this._linesIndexBuffer = null;
  30164. }
  30165. // Remove from mesh
  30166. var index = this._mesh.subMeshes.indexOf(this);
  30167. this._mesh.subMeshes.splice(index, 1);
  30168. };
  30169. // Statics
  30170. /**
  30171. * Creates a new Submesh from the passed parameters :
  30172. * - materialIndex (integer) : the index of the main mesh material.
  30173. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30174. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30175. * - mesh (Mesh) : the main mesh to create the submesh from.
  30176. * - renderingMesh (optional Mesh) : rendering mesh.
  30177. */
  30178. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30179. var minVertexIndex = Number.MAX_VALUE;
  30180. var maxVertexIndex = -Number.MAX_VALUE;
  30181. renderingMesh = (renderingMesh || mesh);
  30182. var indices = renderingMesh.getIndices();
  30183. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30184. var vertexIndex = indices[index];
  30185. if (vertexIndex < minVertexIndex)
  30186. minVertexIndex = vertexIndex;
  30187. if (vertexIndex > maxVertexIndex)
  30188. maxVertexIndex = vertexIndex;
  30189. }
  30190. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30191. };
  30192. return SubMesh;
  30193. }(BaseSubMesh));
  30194. BABYLON.SubMesh = SubMesh;
  30195. })(BABYLON || (BABYLON = {}));
  30196. //# sourceMappingURL=babylon.subMesh.js.map
  30197. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30198. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30199. s = arguments[i];
  30200. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30201. t[p] = s[p];
  30202. }
  30203. return t;
  30204. };
  30205. var BABYLON;
  30206. (function (BABYLON) {
  30207. /**
  30208. * Manages the defines for the Material.
  30209. */
  30210. var MaterialDefines = /** @class */ (function () {
  30211. function MaterialDefines() {
  30212. this._isDirty = true;
  30213. this._areLightsDirty = true;
  30214. this._areAttributesDirty = true;
  30215. this._areTexturesDirty = true;
  30216. this._areFresnelDirty = true;
  30217. this._areMiscDirty = true;
  30218. this._areImageProcessingDirty = true;
  30219. this._normals = false;
  30220. this._uvs = false;
  30221. this._needNormals = false;
  30222. this._needUVs = false;
  30223. }
  30224. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30225. /**
  30226. * Specifies if the material needs to be re-calculated.
  30227. */
  30228. get: function () {
  30229. return this._isDirty;
  30230. },
  30231. enumerable: true,
  30232. configurable: true
  30233. });
  30234. /**
  30235. * Marks the material to indicate that it has been re-calculated.
  30236. */
  30237. MaterialDefines.prototype.markAsProcessed = function () {
  30238. this._isDirty = false;
  30239. this._areAttributesDirty = false;
  30240. this._areTexturesDirty = false;
  30241. this._areFresnelDirty = false;
  30242. this._areLightsDirty = false;
  30243. this._areMiscDirty = false;
  30244. this._areImageProcessingDirty = false;
  30245. };
  30246. /**
  30247. * Marks the material to indicate that it needs to be re-calculated.
  30248. */
  30249. MaterialDefines.prototype.markAsUnprocessed = function () {
  30250. this._isDirty = true;
  30251. };
  30252. /**
  30253. * Marks the material to indicate all of its defines need to be re-calculated.
  30254. */
  30255. MaterialDefines.prototype.markAllAsDirty = function () {
  30256. this._areTexturesDirty = true;
  30257. this._areAttributesDirty = true;
  30258. this._areLightsDirty = true;
  30259. this._areFresnelDirty = true;
  30260. this._areMiscDirty = true;
  30261. this._areImageProcessingDirty = true;
  30262. this._isDirty = true;
  30263. };
  30264. /**
  30265. * Marks the material to indicate that image processing needs to be re-calculated.
  30266. */
  30267. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30268. this._areImageProcessingDirty = true;
  30269. this._isDirty = true;
  30270. };
  30271. /**
  30272. * Marks the material to indicate the lights need to be re-calculated.
  30273. */
  30274. MaterialDefines.prototype.markAsLightDirty = function () {
  30275. this._areLightsDirty = true;
  30276. this._isDirty = true;
  30277. };
  30278. /**
  30279. * Marks the attribute state as changed.
  30280. */
  30281. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30282. this._areAttributesDirty = true;
  30283. this._isDirty = true;
  30284. };
  30285. /**
  30286. * Marks the texture state as changed.
  30287. */
  30288. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30289. this._areTexturesDirty = true;
  30290. this._isDirty = true;
  30291. };
  30292. /**
  30293. * Marks the fresnel state as changed.
  30294. */
  30295. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30296. this._areFresnelDirty = true;
  30297. this._isDirty = true;
  30298. };
  30299. /**
  30300. * Marks the misc state as changed.
  30301. */
  30302. MaterialDefines.prototype.markAsMiscDirty = function () {
  30303. this._areMiscDirty = true;
  30304. this._isDirty = true;
  30305. };
  30306. /**
  30307. * Rebuilds the material defines.
  30308. */
  30309. MaterialDefines.prototype.rebuild = function () {
  30310. if (this._keys) {
  30311. delete this._keys;
  30312. }
  30313. this._keys = [];
  30314. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30315. var key = _a[_i];
  30316. if (key[0] === "_") {
  30317. continue;
  30318. }
  30319. this._keys.push(key);
  30320. }
  30321. };
  30322. /**
  30323. * Specifies if two material defines are equal.
  30324. * @param other - A material define instance to compare to.
  30325. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30326. */
  30327. MaterialDefines.prototype.isEqual = function (other) {
  30328. if (this._keys.length !== other._keys.length) {
  30329. return false;
  30330. }
  30331. for (var index = 0; index < this._keys.length; index++) {
  30332. var prop = this._keys[index];
  30333. if (this[prop] !== other[prop]) {
  30334. return false;
  30335. }
  30336. }
  30337. return true;
  30338. };
  30339. /**
  30340. * Clones this instance's defines to another instance.
  30341. * @param other - material defines to clone values to.
  30342. */
  30343. MaterialDefines.prototype.cloneTo = function (other) {
  30344. if (this._keys.length !== other._keys.length) {
  30345. other._keys = this._keys.slice(0);
  30346. }
  30347. for (var index = 0; index < this._keys.length; index++) {
  30348. var prop = this._keys[index];
  30349. other[prop] = this[prop];
  30350. }
  30351. };
  30352. /**
  30353. * Resets the material define values.
  30354. */
  30355. MaterialDefines.prototype.reset = function () {
  30356. for (var index = 0; index < this._keys.length; index++) {
  30357. var prop = this._keys[index];
  30358. if (typeof (this[prop]) === "number") {
  30359. this[prop] = 0;
  30360. }
  30361. else {
  30362. this[prop] = false;
  30363. }
  30364. }
  30365. };
  30366. /**
  30367. * Converts the material define values to a string.
  30368. * @returns - String of material define information.
  30369. */
  30370. MaterialDefines.prototype.toString = function () {
  30371. var result = "";
  30372. for (var index = 0; index < this._keys.length; index++) {
  30373. var prop = this._keys[index];
  30374. var value = this[prop];
  30375. if (typeof (value) === "number") {
  30376. result += "#define " + prop + " " + this[prop] + "\n";
  30377. }
  30378. else if (value) {
  30379. result += "#define " + prop + "\n";
  30380. }
  30381. }
  30382. return result;
  30383. };
  30384. return MaterialDefines;
  30385. }());
  30386. BABYLON.MaterialDefines = MaterialDefines;
  30387. /**
  30388. * This offers the main features of a material in BJS.
  30389. */
  30390. var Material = /** @class */ (function () {
  30391. /**
  30392. * Creates a material instance.
  30393. * @param name - The name of the material.
  30394. * @param scene - The BJS scene to reference.
  30395. * @param doNotAdd - Specifies if the material should be added to the scene.
  30396. */
  30397. function Material(name, scene, doNotAdd) {
  30398. /**
  30399. * Specifies if the ready state should be checked on each call.
  30400. */
  30401. this.checkReadyOnEveryCall = false;
  30402. /**
  30403. * Specifies if the ready state should be checked once.
  30404. */
  30405. this.checkReadyOnlyOnce = false;
  30406. /**
  30407. * The state of the material.
  30408. */
  30409. this.state = "";
  30410. /**
  30411. * The alpha value of the material.
  30412. */
  30413. this._alpha = 1.0;
  30414. /**
  30415. * Specifies if back face culling is enabled.
  30416. */
  30417. this._backFaceCulling = true;
  30418. /**
  30419. * Specifies if the material should be serialized.
  30420. */
  30421. this.doNotSerialize = false;
  30422. /**
  30423. * Specifies if the effect should be stored on sub meshes.
  30424. */
  30425. this.storeEffectOnSubMeshes = false;
  30426. /**
  30427. * An event triggered when the material is disposed.
  30428. * @type {BABYLON.Observable}
  30429. */
  30430. this.onDisposeObservable = new BABYLON.Observable();
  30431. /**
  30432. * An event triggered when the material is bound.
  30433. * @type {BABYLON.Observable}
  30434. */
  30435. this.onBindObservable = new BABYLON.Observable();
  30436. /**
  30437. * An event triggered when the material is unbound.
  30438. * @type {BABYLON.Observable}
  30439. */
  30440. this.onUnBindObservable = new BABYLON.Observable();
  30441. /**
  30442. * Stores the value of the alpha mode.
  30443. */
  30444. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30445. /**
  30446. * Stores the state of the need depth pre-pass value.
  30447. */
  30448. this._needDepthPrePass = false;
  30449. /**
  30450. * Specifies if depth writing should be disabled.
  30451. */
  30452. this.disableDepthWrite = false;
  30453. /**
  30454. * Specifies if depth writing should be forced.
  30455. */
  30456. this.forceDepthWrite = false;
  30457. /**
  30458. * Specifies if there should be a separate pass for culling.
  30459. */
  30460. this.separateCullingPass = false;
  30461. /**
  30462. * Stores the state specifing if fog should be enabled.
  30463. */
  30464. this._fogEnabled = true;
  30465. /**
  30466. * Stores the size of points.
  30467. */
  30468. this.pointSize = 1.0;
  30469. /**
  30470. * Stores the z offset value.
  30471. */
  30472. this.zOffset = 0;
  30473. /**
  30474. * Specifies if the material was previously ready.
  30475. */
  30476. this._wasPreviouslyReady = false;
  30477. /**
  30478. * Stores the fill mode state.
  30479. */
  30480. this._fillMode = Material.TriangleFillMode;
  30481. this.name = name;
  30482. this.id = name || BABYLON.Tools.RandomId();
  30483. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30484. if (this._scene.useRightHandedSystem) {
  30485. this.sideOrientation = Material.ClockWiseSideOrientation;
  30486. }
  30487. else {
  30488. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30489. }
  30490. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30491. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30492. if (!doNotAdd) {
  30493. this._scene.materials.push(this);
  30494. }
  30495. }
  30496. Object.defineProperty(Material, "TriangleFillMode", {
  30497. /**
  30498. * Returns the triangle fill mode.
  30499. */
  30500. get: function () {
  30501. return Material._TriangleFillMode;
  30502. },
  30503. enumerable: true,
  30504. configurable: true
  30505. });
  30506. Object.defineProperty(Material, "WireFrameFillMode", {
  30507. /**
  30508. * Returns the wireframe mode.
  30509. */
  30510. get: function () {
  30511. return Material._WireFrameFillMode;
  30512. },
  30513. enumerable: true,
  30514. configurable: true
  30515. });
  30516. Object.defineProperty(Material, "PointFillMode", {
  30517. /**
  30518. * Returns the point fill mode.
  30519. */
  30520. get: function () {
  30521. return Material._PointFillMode;
  30522. },
  30523. enumerable: true,
  30524. configurable: true
  30525. });
  30526. Object.defineProperty(Material, "PointListDrawMode", {
  30527. /**
  30528. * Returns the point list draw mode.
  30529. */
  30530. get: function () {
  30531. return Material._PointListDrawMode;
  30532. },
  30533. enumerable: true,
  30534. configurable: true
  30535. });
  30536. Object.defineProperty(Material, "LineListDrawMode", {
  30537. /**
  30538. * Returns the line list draw mode.
  30539. */
  30540. get: function () {
  30541. return Material._LineListDrawMode;
  30542. },
  30543. enumerable: true,
  30544. configurable: true
  30545. });
  30546. Object.defineProperty(Material, "LineLoopDrawMode", {
  30547. /**
  30548. * Returns the line loop draw mode.
  30549. */
  30550. get: function () {
  30551. return Material._LineLoopDrawMode;
  30552. },
  30553. enumerable: true,
  30554. configurable: true
  30555. });
  30556. Object.defineProperty(Material, "LineStripDrawMode", {
  30557. /**
  30558. * Returns the line strip draw mode.
  30559. */
  30560. get: function () {
  30561. return Material._LineStripDrawMode;
  30562. },
  30563. enumerable: true,
  30564. configurable: true
  30565. });
  30566. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30567. /**
  30568. * Returns the triangle strip draw mode.
  30569. */
  30570. get: function () {
  30571. return Material._TriangleStripDrawMode;
  30572. },
  30573. enumerable: true,
  30574. configurable: true
  30575. });
  30576. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30577. /**
  30578. * Returns the triangle fan draw mode.
  30579. */
  30580. get: function () {
  30581. return Material._TriangleFanDrawMode;
  30582. },
  30583. enumerable: true,
  30584. configurable: true
  30585. });
  30586. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30587. /**
  30588. * Returns the clock-wise side orientation.
  30589. */
  30590. get: function () {
  30591. return Material._ClockWiseSideOrientation;
  30592. },
  30593. enumerable: true,
  30594. configurable: true
  30595. });
  30596. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30597. /**
  30598. * Returns the counter clock-wise side orientation.
  30599. */
  30600. get: function () {
  30601. return Material._CounterClockWiseSideOrientation;
  30602. },
  30603. enumerable: true,
  30604. configurable: true
  30605. });
  30606. Object.defineProperty(Material, "TextureDirtyFlag", {
  30607. /**
  30608. * Returns the dirty texture flag value.
  30609. */
  30610. get: function () {
  30611. return Material._TextureDirtyFlag;
  30612. },
  30613. enumerable: true,
  30614. configurable: true
  30615. });
  30616. Object.defineProperty(Material, "LightDirtyFlag", {
  30617. /**
  30618. * Returns the dirty light flag value.
  30619. */
  30620. get: function () {
  30621. return Material._LightDirtyFlag;
  30622. },
  30623. enumerable: true,
  30624. configurable: true
  30625. });
  30626. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30627. /**
  30628. * Returns the dirty fresnel flag value.
  30629. */
  30630. get: function () {
  30631. return Material._FresnelDirtyFlag;
  30632. },
  30633. enumerable: true,
  30634. configurable: true
  30635. });
  30636. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30637. /**
  30638. * Returns the dirty attributes flag value.
  30639. */
  30640. get: function () {
  30641. return Material._AttributesDirtyFlag;
  30642. },
  30643. enumerable: true,
  30644. configurable: true
  30645. });
  30646. Object.defineProperty(Material, "MiscDirtyFlag", {
  30647. /**
  30648. * Returns the dirty misc flag value.
  30649. */
  30650. get: function () {
  30651. return Material._MiscDirtyFlag;
  30652. },
  30653. enumerable: true,
  30654. configurable: true
  30655. });
  30656. Object.defineProperty(Material.prototype, "alpha", {
  30657. /**
  30658. * Gets the alpha value of the material.
  30659. */
  30660. get: function () {
  30661. return this._alpha;
  30662. },
  30663. /**
  30664. * Sets the alpha value of the material.
  30665. */
  30666. set: function (value) {
  30667. if (this._alpha === value) {
  30668. return;
  30669. }
  30670. this._alpha = value;
  30671. this.markAsDirty(Material.MiscDirtyFlag);
  30672. },
  30673. enumerable: true,
  30674. configurable: true
  30675. });
  30676. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30677. /**
  30678. * Gets the back-face culling state.
  30679. */
  30680. get: function () {
  30681. return this._backFaceCulling;
  30682. },
  30683. /**
  30684. * Sets the back-face culling state.
  30685. */
  30686. set: function (value) {
  30687. if (this._backFaceCulling === value) {
  30688. return;
  30689. }
  30690. this._backFaceCulling = value;
  30691. this.markAsDirty(Material.TextureDirtyFlag);
  30692. },
  30693. enumerable: true,
  30694. configurable: true
  30695. });
  30696. Object.defineProperty(Material.prototype, "onDispose", {
  30697. /**
  30698. * Called during a dispose event.
  30699. */
  30700. set: function (callback) {
  30701. if (this._onDisposeObserver) {
  30702. this.onDisposeObservable.remove(this._onDisposeObserver);
  30703. }
  30704. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30705. },
  30706. enumerable: true,
  30707. configurable: true
  30708. });
  30709. Object.defineProperty(Material.prototype, "onBind", {
  30710. /**
  30711. * Called during a bind event.
  30712. */
  30713. set: function (callback) {
  30714. if (this._onBindObserver) {
  30715. this.onBindObservable.remove(this._onBindObserver);
  30716. }
  30717. this._onBindObserver = this.onBindObservable.add(callback);
  30718. },
  30719. enumerable: true,
  30720. configurable: true
  30721. });
  30722. Object.defineProperty(Material.prototype, "alphaMode", {
  30723. /**
  30724. * Gets the value of the alpha mode.
  30725. */
  30726. get: function () {
  30727. return this._alphaMode;
  30728. },
  30729. /**
  30730. * Sets the value of the alpha mode.
  30731. */
  30732. set: function (value) {
  30733. if (this._alphaMode === value) {
  30734. return;
  30735. }
  30736. this._alphaMode = value;
  30737. this.markAsDirty(Material.TextureDirtyFlag);
  30738. },
  30739. enumerable: true,
  30740. configurable: true
  30741. });
  30742. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  30743. /**
  30744. * Gets the depth pre-pass value.
  30745. */
  30746. get: function () {
  30747. return this._needDepthPrePass;
  30748. },
  30749. /**
  30750. * Sets the need depth pre-pass value.
  30751. */
  30752. set: function (value) {
  30753. if (this._needDepthPrePass === value) {
  30754. return;
  30755. }
  30756. this._needDepthPrePass = value;
  30757. if (this._needDepthPrePass) {
  30758. this.checkReadyOnEveryCall = true;
  30759. }
  30760. },
  30761. enumerable: true,
  30762. configurable: true
  30763. });
  30764. Object.defineProperty(Material.prototype, "fogEnabled", {
  30765. /**
  30766. * Gets the value of the fog enabled state.
  30767. */
  30768. get: function () {
  30769. return this._fogEnabled;
  30770. },
  30771. /**
  30772. * Sets the state for enabling fog.
  30773. */
  30774. set: function (value) {
  30775. if (this._fogEnabled === value) {
  30776. return;
  30777. }
  30778. this._fogEnabled = value;
  30779. this.markAsDirty(Material.MiscDirtyFlag);
  30780. },
  30781. enumerable: true,
  30782. configurable: true
  30783. });
  30784. Object.defineProperty(Material.prototype, "wireframe", {
  30785. /**
  30786. * Gets a value specifying if wireframe mode is enabled.
  30787. */
  30788. get: function () {
  30789. return this._fillMode === Material.WireFrameFillMode;
  30790. },
  30791. /**
  30792. * Sets the state of wireframe mode.
  30793. */
  30794. set: function (value) {
  30795. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30796. },
  30797. enumerable: true,
  30798. configurable: true
  30799. });
  30800. Object.defineProperty(Material.prototype, "pointsCloud", {
  30801. /**
  30802. * Gets the value specifying if point clouds are enabled.
  30803. */
  30804. get: function () {
  30805. return this._fillMode === Material.PointFillMode;
  30806. },
  30807. /**
  30808. * Sets the state of point cloud mode.
  30809. */
  30810. set: function (value) {
  30811. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30812. },
  30813. enumerable: true,
  30814. configurable: true
  30815. });
  30816. Object.defineProperty(Material.prototype, "fillMode", {
  30817. /**
  30818. * Gets the material fill mode.
  30819. */
  30820. get: function () {
  30821. return this._fillMode;
  30822. },
  30823. /**
  30824. * Sets the material fill mode.
  30825. */
  30826. set: function (value) {
  30827. if (this._fillMode === value) {
  30828. return;
  30829. }
  30830. this._fillMode = value;
  30831. this.markAsDirty(Material.MiscDirtyFlag);
  30832. },
  30833. enumerable: true,
  30834. configurable: true
  30835. });
  30836. /**
  30837. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30838. * subclasses should override adding information pertainent to themselves.
  30839. * @returns - String with material information.
  30840. */
  30841. Material.prototype.toString = function (fullDetails) {
  30842. var ret = "Name: " + this.name;
  30843. if (fullDetails) {
  30844. }
  30845. return ret;
  30846. };
  30847. /**
  30848. * Gets the class name of the material.
  30849. * @returns - String with the class name of the material.
  30850. */
  30851. Material.prototype.getClassName = function () {
  30852. return "Material";
  30853. };
  30854. Object.defineProperty(Material.prototype, "isFrozen", {
  30855. /**
  30856. * Specifies if updates for the material been locked.
  30857. */
  30858. get: function () {
  30859. return this.checkReadyOnlyOnce;
  30860. },
  30861. enumerable: true,
  30862. configurable: true
  30863. });
  30864. /**
  30865. * Locks updates for the material.
  30866. */
  30867. Material.prototype.freeze = function () {
  30868. this.checkReadyOnlyOnce = true;
  30869. };
  30870. /**
  30871. * Unlocks updates for the material.
  30872. */
  30873. Material.prototype.unfreeze = function () {
  30874. this.checkReadyOnlyOnce = false;
  30875. };
  30876. /**
  30877. * Specifies if the material is ready to be used.
  30878. * @param mesh - BJS mesh.
  30879. * @param useInstances - Specifies if instances should be used.
  30880. * @returns - Boolean indicating if the material is ready to be used.
  30881. */
  30882. Material.prototype.isReady = function (mesh, useInstances) {
  30883. return true;
  30884. };
  30885. /**
  30886. * Specifies that the submesh is ready to be used.
  30887. * @param mesh - BJS mesh.
  30888. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  30889. * @param useInstances - Specifies that instances should be used.
  30890. * @returns - boolean indicating that the submesh is ready or not.
  30891. */
  30892. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30893. return false;
  30894. };
  30895. /**
  30896. * Returns the material effect.
  30897. * @returns - Nullable material effect.
  30898. */
  30899. Material.prototype.getEffect = function () {
  30900. return this._effect;
  30901. };
  30902. /**
  30903. * Returns the BJS scene.
  30904. * @returns - BJS Scene.
  30905. */
  30906. Material.prototype.getScene = function () {
  30907. return this._scene;
  30908. };
  30909. /**
  30910. * Specifies if the material will require alpha blending
  30911. * @returns - Boolean specifying if alpha blending is needed.
  30912. */
  30913. Material.prototype.needAlphaBlending = function () {
  30914. return (this.alpha < 1.0);
  30915. };
  30916. /**
  30917. * Specifies if the mesh will require alpha blending.
  30918. * @param mesh - BJS mesh.
  30919. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  30920. */
  30921. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  30922. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  30923. };
  30924. /**
  30925. * Specifies if this material should be rendered in alpha test mode.
  30926. * @returns - Boolean specifying if an alpha test is needed.
  30927. */
  30928. Material.prototype.needAlphaTesting = function () {
  30929. return false;
  30930. };
  30931. /**
  30932. * Gets the texture used for the alpha test.
  30933. * @returns - Nullable alpha test texture.
  30934. */
  30935. Material.prototype.getAlphaTestTexture = function () {
  30936. return null;
  30937. };
  30938. /**
  30939. * Marks the material to indicate that it needs to be re-calculated.
  30940. */
  30941. Material.prototype.markDirty = function () {
  30942. this._wasPreviouslyReady = false;
  30943. };
  30944. Material.prototype._preBind = function (effect, overrideOrientation) {
  30945. if (overrideOrientation === void 0) { overrideOrientation = null; }
  30946. var engine = this._scene.getEngine();
  30947. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  30948. var reverse = orientation === Material.ClockWiseSideOrientation;
  30949. engine.enableEffect(effect ? effect : this._effect);
  30950. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  30951. return reverse;
  30952. };
  30953. /**
  30954. * Binds the material to the mesh.
  30955. * @param world - World transformation matrix.
  30956. * @param mesh - Mesh to bind the material to.
  30957. */
  30958. Material.prototype.bind = function (world, mesh) {
  30959. };
  30960. /**
  30961. * Binds the submesh to the material.
  30962. * @param world - World transformation matrix.
  30963. * @param mesh - Mesh containing the submesh.
  30964. * @param subMesh - Submesh to bind the material to.
  30965. */
  30966. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30967. };
  30968. /**
  30969. * Binds the world matrix to the material.
  30970. * @param world - World transformation matrix.
  30971. */
  30972. Material.prototype.bindOnlyWorldMatrix = function (world) {
  30973. };
  30974. /**
  30975. * Binds the scene's uniform buffer to the effect.
  30976. * @param effect - Effect to bind to the scene uniform buffer.
  30977. * @param sceneUbo - Scene uniform buffer.
  30978. */
  30979. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  30980. sceneUbo.bindToEffect(effect, "Scene");
  30981. };
  30982. /**
  30983. * Binds the view matrix to the effect.
  30984. * @param effect - Effect to bind the view matrix to.
  30985. */
  30986. Material.prototype.bindView = function (effect) {
  30987. if (!this._useUBO) {
  30988. effect.setMatrix("view", this.getScene().getViewMatrix());
  30989. }
  30990. else {
  30991. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30992. }
  30993. };
  30994. /**
  30995. * Binds the view projection matrix to the effect.
  30996. * @param effect - Effect to bind the view projection matrix to.
  30997. */
  30998. Material.prototype.bindViewProjection = function (effect) {
  30999. if (!this._useUBO) {
  31000. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31001. }
  31002. else {
  31003. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31004. }
  31005. };
  31006. /**
  31007. * Specifies if material alpha testing should be turned on for the mesh.
  31008. * @param mesh - BJS mesh.
  31009. */
  31010. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31011. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31012. };
  31013. /**
  31014. * Processes to execute after binding the material to a mesh.
  31015. * @param mesh - BJS mesh.
  31016. */
  31017. Material.prototype._afterBind = function (mesh) {
  31018. this._scene._cachedMaterial = this;
  31019. if (mesh) {
  31020. this._scene._cachedVisibility = mesh.visibility;
  31021. }
  31022. else {
  31023. this._scene._cachedVisibility = 1;
  31024. }
  31025. if (mesh) {
  31026. this.onBindObservable.notifyObservers(mesh);
  31027. }
  31028. if (this.disableDepthWrite) {
  31029. var engine = this._scene.getEngine();
  31030. this._cachedDepthWriteState = engine.getDepthWrite();
  31031. engine.setDepthWrite(false);
  31032. }
  31033. };
  31034. /**
  31035. * Unbinds the material from the mesh.
  31036. */
  31037. Material.prototype.unbind = function () {
  31038. this.onUnBindObservable.notifyObservers(this);
  31039. if (this.disableDepthWrite) {
  31040. var engine = this._scene.getEngine();
  31041. engine.setDepthWrite(this._cachedDepthWriteState);
  31042. }
  31043. };
  31044. /**
  31045. * Gets the active textures from the material.
  31046. * @returns - Array of textures.
  31047. */
  31048. Material.prototype.getActiveTextures = function () {
  31049. return [];
  31050. };
  31051. /**
  31052. * Specifies if the material uses a texture.
  31053. * @param texture - Texture to check against the material.
  31054. * @returns - Boolean specifying if the material uses the texture.
  31055. */
  31056. Material.prototype.hasTexture = function (texture) {
  31057. return false;
  31058. };
  31059. /**
  31060. * Makes a duplicate of the material, and gives it a new name.
  31061. * @param name - Name to call the duplicated material.
  31062. * @returns - Nullable cloned material
  31063. */
  31064. Material.prototype.clone = function (name) {
  31065. return null;
  31066. };
  31067. /**
  31068. * Gets the meshes bound to the material.
  31069. * @returns - Array of meshes bound to the material.
  31070. */
  31071. Material.prototype.getBindedMeshes = function () {
  31072. var result = new Array();
  31073. for (var index = 0; index < this._scene.meshes.length; index++) {
  31074. var mesh = this._scene.meshes[index];
  31075. if (mesh.material === this) {
  31076. result.push(mesh);
  31077. }
  31078. }
  31079. return result;
  31080. };
  31081. /**
  31082. * Force shader compilation
  31083. * @param mesh - BJS mesh.
  31084. * @param onCompiled - function to execute once the material is compiled.
  31085. * @param options - options to pass to this function.
  31086. */
  31087. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31088. var _this = this;
  31089. var localOptions = __assign({ clipPlane: false }, options);
  31090. var subMesh = new BABYLON.BaseSubMesh();
  31091. var scene = this.getScene();
  31092. var checkReady = function () {
  31093. if (!_this._scene || !_this._scene.getEngine()) {
  31094. return;
  31095. }
  31096. if (subMesh._materialDefines) {
  31097. subMesh._materialDefines._renderId = -1;
  31098. }
  31099. var clipPlaneState = scene.clipPlane;
  31100. if (localOptions.clipPlane) {
  31101. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31102. }
  31103. if (_this.storeEffectOnSubMeshes) {
  31104. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31105. if (onCompiled) {
  31106. onCompiled(_this);
  31107. }
  31108. }
  31109. else {
  31110. setTimeout(checkReady, 16);
  31111. }
  31112. }
  31113. else {
  31114. if (_this.isReady(mesh)) {
  31115. if (onCompiled) {
  31116. onCompiled(_this);
  31117. }
  31118. }
  31119. else {
  31120. setTimeout(checkReady, 16);
  31121. }
  31122. }
  31123. if (localOptions.clipPlane) {
  31124. scene.clipPlane = clipPlaneState;
  31125. }
  31126. };
  31127. checkReady();
  31128. };
  31129. /**
  31130. * Force shader compilation.
  31131. * @param mesh The mesh that will use this material
  31132. * @param options Additional options for compiling the shaders
  31133. * @returns A promise that resolves when the compilation completes
  31134. */
  31135. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31136. var _this = this;
  31137. return new Promise(function (resolve) {
  31138. _this.forceCompilation(mesh, function () {
  31139. resolve();
  31140. }, options);
  31141. });
  31142. };
  31143. /**
  31144. * Marks a define in the material to indicate that it needs to be re-computed.
  31145. * @param flag - Material define flag.
  31146. */
  31147. Material.prototype.markAsDirty = function (flag) {
  31148. if (flag & Material.TextureDirtyFlag) {
  31149. this._markAllSubMeshesAsTexturesDirty();
  31150. }
  31151. if (flag & Material.LightDirtyFlag) {
  31152. this._markAllSubMeshesAsLightsDirty();
  31153. }
  31154. if (flag & Material.FresnelDirtyFlag) {
  31155. this._markAllSubMeshesAsFresnelDirty();
  31156. }
  31157. if (flag & Material.AttributesDirtyFlag) {
  31158. this._markAllSubMeshesAsAttributesDirty();
  31159. }
  31160. if (flag & Material.MiscDirtyFlag) {
  31161. this._markAllSubMeshesAsMiscDirty();
  31162. }
  31163. this.getScene().resetCachedMaterial();
  31164. };
  31165. /**
  31166. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31167. * @param func - function which checks material defines against the submeshes.
  31168. */
  31169. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31170. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31171. var mesh = _a[_i];
  31172. if (!mesh.subMeshes) {
  31173. continue;
  31174. }
  31175. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31176. var subMesh = _c[_b];
  31177. if (subMesh.getMaterial() !== this) {
  31178. continue;
  31179. }
  31180. if (!subMesh._materialDefines) {
  31181. continue;
  31182. }
  31183. func(subMesh._materialDefines);
  31184. }
  31185. }
  31186. };
  31187. /**
  31188. * Indicates that image processing needs to be re-calculated for all submeshes.
  31189. */
  31190. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31191. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31192. };
  31193. /**
  31194. * Indicates that textures need to be re-calculated for all submeshes.
  31195. */
  31196. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31197. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31198. };
  31199. /**
  31200. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31201. */
  31202. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31203. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31204. };
  31205. /**
  31206. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31207. */
  31208. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31209. this._markAllSubMeshesAsDirty(function (defines) {
  31210. defines.markAsFresnelDirty();
  31211. defines.markAsMiscDirty();
  31212. });
  31213. };
  31214. /**
  31215. * Indicates that lights need to be re-calculated for all submeshes.
  31216. */
  31217. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31218. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31219. };
  31220. /**
  31221. * Indicates that attributes need to be re-calculated for all submeshes.
  31222. */
  31223. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31224. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31225. };
  31226. /**
  31227. * Indicates that misc needs to be re-calculated for all submeshes.
  31228. */
  31229. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31230. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31231. };
  31232. /**
  31233. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31234. */
  31235. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31236. this._markAllSubMeshesAsDirty(function (defines) {
  31237. defines.markAsTexturesDirty();
  31238. defines.markAsMiscDirty();
  31239. });
  31240. };
  31241. /**
  31242. * Disposes the material.
  31243. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31244. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31245. */
  31246. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31247. // Animations
  31248. this.getScene().stopAnimation(this);
  31249. // Remove from scene
  31250. var index = this._scene.materials.indexOf(this);
  31251. if (index >= 0) {
  31252. this._scene.materials.splice(index, 1);
  31253. }
  31254. // Remove from meshes
  31255. for (index = 0; index < this._scene.meshes.length; index++) {
  31256. var mesh = this._scene.meshes[index];
  31257. if (mesh.material === this) {
  31258. mesh.material = null;
  31259. if (mesh.geometry) {
  31260. var geometry = (mesh.geometry);
  31261. if (this.storeEffectOnSubMeshes) {
  31262. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31263. var subMesh = _a[_i];
  31264. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31265. if (forceDisposeEffect && subMesh._materialEffect) {
  31266. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31267. }
  31268. }
  31269. }
  31270. else {
  31271. geometry._releaseVertexArrayObject(this._effect);
  31272. }
  31273. }
  31274. }
  31275. }
  31276. this._uniformBuffer.dispose();
  31277. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31278. if (forceDisposeEffect && this._effect) {
  31279. if (!this.storeEffectOnSubMeshes) {
  31280. this._scene.getEngine()._releaseEffect(this._effect);
  31281. }
  31282. this._effect = null;
  31283. }
  31284. // Callback
  31285. this.onDisposeObservable.notifyObservers(this);
  31286. this.onDisposeObservable.clear();
  31287. this.onBindObservable.clear();
  31288. this.onUnBindObservable.clear();
  31289. };
  31290. /**
  31291. * Serializes this material.
  31292. * @returns - serialized material object.
  31293. */
  31294. Material.prototype.serialize = function () {
  31295. return BABYLON.SerializationHelper.Serialize(this);
  31296. };
  31297. /**
  31298. * Creates a MultiMaterial from parse MultiMaterial data.
  31299. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31300. * @param scene - BJS scene.
  31301. * @returns - MultiMaterial.
  31302. */
  31303. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31304. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31305. multiMaterial.id = parsedMultiMaterial.id;
  31306. if (BABYLON.Tags) {
  31307. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31308. }
  31309. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31310. var subMatId = parsedMultiMaterial.materials[matIndex];
  31311. if (subMatId) {
  31312. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31313. }
  31314. else {
  31315. multiMaterial.subMaterials.push(null);
  31316. }
  31317. }
  31318. return multiMaterial;
  31319. };
  31320. /**
  31321. * Creates a material from parsed material data.
  31322. * @param parsedMaterial - Parsed material data.
  31323. * @param scene - BJS scene.
  31324. * @param rootUrl - Root URL containing the material information.
  31325. * @returns - Parsed material.
  31326. */
  31327. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31328. if (!parsedMaterial.customType) {
  31329. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31330. }
  31331. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31332. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31333. if (!BABYLON.LegacyPBRMaterial) {
  31334. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31335. return;
  31336. }
  31337. }
  31338. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31339. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31340. ;
  31341. };
  31342. // Triangle views
  31343. Material._TriangleFillMode = 0;
  31344. Material._WireFrameFillMode = 1;
  31345. Material._PointFillMode = 2;
  31346. // Draw modes
  31347. Material._PointListDrawMode = 3;
  31348. Material._LineListDrawMode = 4;
  31349. Material._LineLoopDrawMode = 5;
  31350. Material._LineStripDrawMode = 6;
  31351. Material._TriangleStripDrawMode = 7;
  31352. Material._TriangleFanDrawMode = 8;
  31353. /**
  31354. * Stores the clock-wise side orientation.
  31355. */
  31356. Material._ClockWiseSideOrientation = 0;
  31357. /**
  31358. * Stores the counter clock-wise side orientation.
  31359. */
  31360. Material._CounterClockWiseSideOrientation = 1;
  31361. /**
  31362. * The dirty texture flag value.
  31363. */
  31364. Material._TextureDirtyFlag = 1;
  31365. /**
  31366. * The dirty light flag value.
  31367. */
  31368. Material._LightDirtyFlag = 2;
  31369. /**
  31370. * The dirty fresnel flag value.
  31371. */
  31372. Material._FresnelDirtyFlag = 4;
  31373. /**
  31374. * The dirty attribute flag value.
  31375. */
  31376. Material._AttributesDirtyFlag = 8;
  31377. /**
  31378. * The dirty misc flag value.
  31379. */
  31380. Material._MiscDirtyFlag = 16;
  31381. __decorate([
  31382. BABYLON.serialize()
  31383. ], Material.prototype, "id", void 0);
  31384. __decorate([
  31385. BABYLON.serialize()
  31386. ], Material.prototype, "name", void 0);
  31387. __decorate([
  31388. BABYLON.serialize()
  31389. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31390. __decorate([
  31391. BABYLON.serialize()
  31392. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31393. __decorate([
  31394. BABYLON.serialize()
  31395. ], Material.prototype, "state", void 0);
  31396. __decorate([
  31397. BABYLON.serialize("alpha")
  31398. ], Material.prototype, "_alpha", void 0);
  31399. __decorate([
  31400. BABYLON.serialize("backFaceCulling")
  31401. ], Material.prototype, "_backFaceCulling", void 0);
  31402. __decorate([
  31403. BABYLON.serialize()
  31404. ], Material.prototype, "sideOrientation", void 0);
  31405. __decorate([
  31406. BABYLON.serialize("alphaMode")
  31407. ], Material.prototype, "_alphaMode", void 0);
  31408. __decorate([
  31409. BABYLON.serialize()
  31410. ], Material.prototype, "_needDepthPrePass", void 0);
  31411. __decorate([
  31412. BABYLON.serialize()
  31413. ], Material.prototype, "disableDepthWrite", void 0);
  31414. __decorate([
  31415. BABYLON.serialize()
  31416. ], Material.prototype, "forceDepthWrite", void 0);
  31417. __decorate([
  31418. BABYLON.serialize()
  31419. ], Material.prototype, "separateCullingPass", void 0);
  31420. __decorate([
  31421. BABYLON.serialize("fogEnabled")
  31422. ], Material.prototype, "_fogEnabled", void 0);
  31423. __decorate([
  31424. BABYLON.serialize()
  31425. ], Material.prototype, "pointSize", void 0);
  31426. __decorate([
  31427. BABYLON.serialize()
  31428. ], Material.prototype, "zOffset", void 0);
  31429. __decorate([
  31430. BABYLON.serialize()
  31431. ], Material.prototype, "wireframe", null);
  31432. __decorate([
  31433. BABYLON.serialize()
  31434. ], Material.prototype, "pointsCloud", null);
  31435. __decorate([
  31436. BABYLON.serialize()
  31437. ], Material.prototype, "fillMode", null);
  31438. return Material;
  31439. }());
  31440. BABYLON.Material = Material;
  31441. })(BABYLON || (BABYLON = {}));
  31442. //# sourceMappingURL=babylon.material.js.map
  31443. var BABYLON;
  31444. (function (BABYLON) {
  31445. var UniformBuffer = /** @class */ (function () {
  31446. /**
  31447. * Uniform buffer objects.
  31448. *
  31449. * Handles blocks of uniform on the GPU.
  31450. *
  31451. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31452. *
  31453. * For more information, please refer to :
  31454. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31455. */
  31456. function UniformBuffer(engine, data, dynamic) {
  31457. this._engine = engine;
  31458. this._noUBO = !engine.supportsUniformBuffers;
  31459. this._dynamic = dynamic;
  31460. this._data = data || [];
  31461. this._uniformLocations = {};
  31462. this._uniformSizes = {};
  31463. this._uniformLocationPointer = 0;
  31464. this._needSync = false;
  31465. if (this._noUBO) {
  31466. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31467. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31468. this.updateFloat = this._updateFloatForEffect;
  31469. this.updateFloat2 = this._updateFloat2ForEffect;
  31470. this.updateFloat3 = this._updateFloat3ForEffect;
  31471. this.updateFloat4 = this._updateFloat4ForEffect;
  31472. this.updateMatrix = this._updateMatrixForEffect;
  31473. this.updateVector3 = this._updateVector3ForEffect;
  31474. this.updateVector4 = this._updateVector4ForEffect;
  31475. this.updateColor3 = this._updateColor3ForEffect;
  31476. this.updateColor4 = this._updateColor4ForEffect;
  31477. }
  31478. else {
  31479. this._engine._uniformBuffers.push(this);
  31480. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31481. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31482. this.updateFloat = this._updateFloatForUniform;
  31483. this.updateFloat2 = this._updateFloat2ForUniform;
  31484. this.updateFloat3 = this._updateFloat3ForUniform;
  31485. this.updateFloat4 = this._updateFloat4ForUniform;
  31486. this.updateMatrix = this._updateMatrixForUniform;
  31487. this.updateVector3 = this._updateVector3ForUniform;
  31488. this.updateVector4 = this._updateVector4ForUniform;
  31489. this.updateColor3 = this._updateColor3ForUniform;
  31490. this.updateColor4 = this._updateColor4ForUniform;
  31491. }
  31492. }
  31493. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31494. // Properties
  31495. /**
  31496. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31497. * or just falling back on setUniformXXX calls.
  31498. */
  31499. get: function () {
  31500. return !this._noUBO;
  31501. },
  31502. enumerable: true,
  31503. configurable: true
  31504. });
  31505. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31506. /**
  31507. * Indicates if the WebGL underlying uniform buffer is in sync
  31508. * with the javascript cache data.
  31509. */
  31510. get: function () {
  31511. return !this._needSync;
  31512. },
  31513. enumerable: true,
  31514. configurable: true
  31515. });
  31516. /**
  31517. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31518. * Also, a dynamic UniformBuffer will disable cache verification and always
  31519. * update the underlying WebGL uniform buffer to the GPU.
  31520. */
  31521. UniformBuffer.prototype.isDynamic = function () {
  31522. return this._dynamic !== undefined;
  31523. };
  31524. /**
  31525. * The data cache on JS side.
  31526. */
  31527. UniformBuffer.prototype.getData = function () {
  31528. return this._bufferData;
  31529. };
  31530. /**
  31531. * The underlying WebGL Uniform buffer.
  31532. */
  31533. UniformBuffer.prototype.getBuffer = function () {
  31534. return this._buffer;
  31535. };
  31536. /**
  31537. * std140 layout specifies how to align data within an UBO structure.
  31538. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31539. * for specs.
  31540. */
  31541. UniformBuffer.prototype._fillAlignment = function (size) {
  31542. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31543. // and 4x4 matrices
  31544. // TODO : change if other types are used
  31545. var alignment;
  31546. if (size <= 2) {
  31547. alignment = size;
  31548. }
  31549. else {
  31550. alignment = 4;
  31551. }
  31552. if ((this._uniformLocationPointer % alignment) !== 0) {
  31553. var oldPointer = this._uniformLocationPointer;
  31554. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31555. var diff = this._uniformLocationPointer - oldPointer;
  31556. for (var i = 0; i < diff; i++) {
  31557. this._data.push(0);
  31558. }
  31559. }
  31560. };
  31561. /**
  31562. * Adds an uniform in the buffer.
  31563. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31564. * for the layout to be correct !
  31565. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31566. * @param {number|number[]} size Data size, or data directly.
  31567. */
  31568. UniformBuffer.prototype.addUniform = function (name, size) {
  31569. if (this._noUBO) {
  31570. return;
  31571. }
  31572. if (this._uniformLocations[name] !== undefined) {
  31573. // Already existing uniform
  31574. return;
  31575. }
  31576. // This function must be called in the order of the shader layout !
  31577. // size can be the size of the uniform, or data directly
  31578. var data;
  31579. if (size instanceof Array) {
  31580. data = size;
  31581. size = data.length;
  31582. }
  31583. else {
  31584. size = size;
  31585. data = [];
  31586. // Fill with zeros
  31587. for (var i = 0; i < size; i++) {
  31588. data.push(0);
  31589. }
  31590. }
  31591. this._fillAlignment(size);
  31592. this._uniformSizes[name] = size;
  31593. this._uniformLocations[name] = this._uniformLocationPointer;
  31594. this._uniformLocationPointer += size;
  31595. for (var i = 0; i < size; i++) {
  31596. this._data.push(data[i]);
  31597. }
  31598. this._needSync = true;
  31599. };
  31600. /**
  31601. * Wrapper for addUniform.
  31602. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31603. * @param {Matrix} mat A 4x4 matrix.
  31604. */
  31605. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31606. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31607. };
  31608. /**
  31609. * Wrapper for addUniform.
  31610. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31611. * @param {number} x
  31612. * @param {number} y
  31613. */
  31614. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31615. var temp = [x, y];
  31616. this.addUniform(name, temp);
  31617. };
  31618. /**
  31619. * Wrapper for addUniform.
  31620. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31621. * @param {number} x
  31622. * @param {number} y
  31623. * @param {number} z
  31624. */
  31625. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31626. var temp = [x, y, z];
  31627. this.addUniform(name, temp);
  31628. };
  31629. /**
  31630. * Wrapper for addUniform.
  31631. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31632. * @param {Color3} color
  31633. */
  31634. UniformBuffer.prototype.addColor3 = function (name, color) {
  31635. var temp = new Array();
  31636. color.toArray(temp);
  31637. this.addUniform(name, temp);
  31638. };
  31639. /**
  31640. * Wrapper for addUniform.
  31641. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31642. * @param {Color3} color
  31643. * @param {number} alpha
  31644. */
  31645. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31646. var temp = new Array();
  31647. color.toArray(temp);
  31648. temp.push(alpha);
  31649. this.addUniform(name, temp);
  31650. };
  31651. /**
  31652. * Wrapper for addUniform.
  31653. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31654. * @param {Vector3} vector
  31655. */
  31656. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31657. var temp = new Array();
  31658. vector.toArray(temp);
  31659. this.addUniform(name, temp);
  31660. };
  31661. /**
  31662. * Wrapper for addUniform.
  31663. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31664. */
  31665. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31666. this.addUniform(name, 12);
  31667. };
  31668. /**
  31669. * Wrapper for addUniform.
  31670. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31671. */
  31672. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31673. this.addUniform(name, 8);
  31674. };
  31675. /**
  31676. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31677. */
  31678. UniformBuffer.prototype.create = function () {
  31679. if (this._noUBO) {
  31680. return;
  31681. }
  31682. if (this._buffer) {
  31683. return; // nothing to do
  31684. }
  31685. // See spec, alignment must be filled as a vec4
  31686. this._fillAlignment(4);
  31687. this._bufferData = new Float32Array(this._data);
  31688. this._rebuild();
  31689. this._needSync = true;
  31690. };
  31691. UniformBuffer.prototype._rebuild = function () {
  31692. if (this._noUBO) {
  31693. return;
  31694. }
  31695. if (this._dynamic) {
  31696. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  31697. }
  31698. else {
  31699. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  31700. }
  31701. };
  31702. /**
  31703. * Updates the WebGL Uniform Buffer on the GPU.
  31704. * If the `dynamic` flag is set to true, no cache comparison is done.
  31705. * Otherwise, the buffer will be updated only if the cache differs.
  31706. */
  31707. UniformBuffer.prototype.update = function () {
  31708. if (!this._buffer) {
  31709. this.create();
  31710. return;
  31711. }
  31712. if (!this._dynamic && !this._needSync) {
  31713. return;
  31714. }
  31715. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  31716. this._needSync = false;
  31717. };
  31718. /**
  31719. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  31720. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31721. * @param {number[]|Float32Array} data Flattened data
  31722. * @param {number} size Size of the data.
  31723. */
  31724. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  31725. var location = this._uniformLocations[uniformName];
  31726. if (location === undefined) {
  31727. if (this._buffer) {
  31728. // Cannot add an uniform if the buffer is already created
  31729. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  31730. return;
  31731. }
  31732. this.addUniform(uniformName, size);
  31733. location = this._uniformLocations[uniformName];
  31734. }
  31735. if (!this._buffer) {
  31736. this.create();
  31737. }
  31738. if (!this._dynamic) {
  31739. // Cache for static uniform buffers
  31740. var changed = false;
  31741. for (var i = 0; i < size; i++) {
  31742. if (this._bufferData[location + i] !== data[i]) {
  31743. changed = true;
  31744. this._bufferData[location + i] = data[i];
  31745. }
  31746. }
  31747. this._needSync = this._needSync || changed;
  31748. }
  31749. else {
  31750. // No cache for dynamic
  31751. for (var i = 0; i < size; i++) {
  31752. this._bufferData[location + i] = data[i];
  31753. }
  31754. }
  31755. };
  31756. // Update methods
  31757. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  31758. // To match std140, matrix must be realigned
  31759. for (var i = 0; i < 3; i++) {
  31760. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  31761. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  31762. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  31763. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31764. }
  31765. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  31766. };
  31767. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  31768. this._currentEffect.setMatrix3x3(name, matrix);
  31769. };
  31770. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  31771. this._currentEffect.setMatrix2x2(name, matrix);
  31772. };
  31773. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  31774. // To match std140, matrix must be realigned
  31775. for (var i = 0; i < 2; i++) {
  31776. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  31777. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  31778. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  31779. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31780. }
  31781. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  31782. };
  31783. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  31784. this._currentEffect.setFloat(name, x);
  31785. };
  31786. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  31787. UniformBuffer._tempBuffer[0] = x;
  31788. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  31789. };
  31790. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  31791. if (suffix === void 0) { suffix = ""; }
  31792. this._currentEffect.setFloat2(name + suffix, x, y);
  31793. };
  31794. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  31795. if (suffix === void 0) { suffix = ""; }
  31796. UniformBuffer._tempBuffer[0] = x;
  31797. UniformBuffer._tempBuffer[1] = y;
  31798. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  31799. };
  31800. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  31801. if (suffix === void 0) { suffix = ""; }
  31802. this._currentEffect.setFloat3(name + suffix, x, y, z);
  31803. };
  31804. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  31805. if (suffix === void 0) { suffix = ""; }
  31806. UniformBuffer._tempBuffer[0] = x;
  31807. UniformBuffer._tempBuffer[1] = y;
  31808. UniformBuffer._tempBuffer[2] = z;
  31809. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31810. };
  31811. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  31812. if (suffix === void 0) { suffix = ""; }
  31813. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  31814. };
  31815. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  31816. if (suffix === void 0) { suffix = ""; }
  31817. UniformBuffer._tempBuffer[0] = x;
  31818. UniformBuffer._tempBuffer[1] = y;
  31819. UniformBuffer._tempBuffer[2] = z;
  31820. UniformBuffer._tempBuffer[3] = w;
  31821. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31822. };
  31823. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  31824. this._currentEffect.setMatrix(name, mat);
  31825. };
  31826. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  31827. this.updateUniform(name, mat.toArray(), 16);
  31828. };
  31829. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  31830. this._currentEffect.setVector3(name, vector);
  31831. };
  31832. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  31833. vector.toArray(UniformBuffer._tempBuffer);
  31834. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31835. };
  31836. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  31837. this._currentEffect.setVector4(name, vector);
  31838. };
  31839. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  31840. vector.toArray(UniformBuffer._tempBuffer);
  31841. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31842. };
  31843. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  31844. if (suffix === void 0) { suffix = ""; }
  31845. this._currentEffect.setColor3(name + suffix, color);
  31846. };
  31847. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  31848. if (suffix === void 0) { suffix = ""; }
  31849. color.toArray(UniformBuffer._tempBuffer);
  31850. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31851. };
  31852. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  31853. if (suffix === void 0) { suffix = ""; }
  31854. this._currentEffect.setColor4(name + suffix, color, alpha);
  31855. };
  31856. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  31857. if (suffix === void 0) { suffix = ""; }
  31858. color.toArray(UniformBuffer._tempBuffer);
  31859. UniformBuffer._tempBuffer[3] = alpha;
  31860. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31861. };
  31862. /**
  31863. * Sets a sampler uniform on the effect.
  31864. * @param {string} name Name of the sampler.
  31865. * @param {Texture} texture
  31866. */
  31867. UniformBuffer.prototype.setTexture = function (name, texture) {
  31868. this._currentEffect.setTexture(name, texture);
  31869. };
  31870. /**
  31871. * Directly updates the value of the uniform in the cache AND on the GPU.
  31872. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31873. * @param {number[]|Float32Array} data Flattened data
  31874. */
  31875. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  31876. this.updateUniform(uniformName, data, data.length);
  31877. this.update();
  31878. };
  31879. /**
  31880. * Binds this uniform buffer to an effect.
  31881. * @param {Effect} effect
  31882. * @param {string} name Name of the uniform block in the shader.
  31883. */
  31884. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  31885. this._currentEffect = effect;
  31886. if (this._noUBO || !this._buffer) {
  31887. return;
  31888. }
  31889. effect.bindUniformBuffer(this._buffer, name);
  31890. };
  31891. /**
  31892. * Disposes the uniform buffer.
  31893. */
  31894. UniformBuffer.prototype.dispose = function () {
  31895. if (this._noUBO) {
  31896. return;
  31897. }
  31898. var index = this._engine._uniformBuffers.indexOf(this);
  31899. if (index !== -1) {
  31900. this._engine._uniformBuffers.splice(index, 1);
  31901. }
  31902. if (!this._buffer) {
  31903. return;
  31904. }
  31905. if (this._engine._releaseBuffer(this._buffer)) {
  31906. this._buffer = null;
  31907. }
  31908. };
  31909. // Pool for avoiding memory leaks
  31910. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  31911. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  31912. return UniformBuffer;
  31913. }());
  31914. BABYLON.UniformBuffer = UniformBuffer;
  31915. })(BABYLON || (BABYLON = {}));
  31916. //# sourceMappingURL=babylon.uniformBuffer.js.map
  31917. var BABYLON;
  31918. (function (BABYLON) {
  31919. var VertexData = /** @class */ (function () {
  31920. function VertexData() {
  31921. }
  31922. VertexData.prototype.set = function (data, kind) {
  31923. switch (kind) {
  31924. case BABYLON.VertexBuffer.PositionKind:
  31925. this.positions = data;
  31926. break;
  31927. case BABYLON.VertexBuffer.NormalKind:
  31928. this.normals = data;
  31929. break;
  31930. case BABYLON.VertexBuffer.TangentKind:
  31931. this.tangents = data;
  31932. break;
  31933. case BABYLON.VertexBuffer.UVKind:
  31934. this.uvs = data;
  31935. break;
  31936. case BABYLON.VertexBuffer.UV2Kind:
  31937. this.uvs2 = data;
  31938. break;
  31939. case BABYLON.VertexBuffer.UV3Kind:
  31940. this.uvs3 = data;
  31941. break;
  31942. case BABYLON.VertexBuffer.UV4Kind:
  31943. this.uvs4 = data;
  31944. break;
  31945. case BABYLON.VertexBuffer.UV5Kind:
  31946. this.uvs5 = data;
  31947. break;
  31948. case BABYLON.VertexBuffer.UV6Kind:
  31949. this.uvs6 = data;
  31950. break;
  31951. case BABYLON.VertexBuffer.ColorKind:
  31952. this.colors = data;
  31953. break;
  31954. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31955. this.matricesIndices = data;
  31956. break;
  31957. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31958. this.matricesWeights = data;
  31959. break;
  31960. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31961. this.matricesIndicesExtra = data;
  31962. break;
  31963. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31964. this.matricesWeightsExtra = data;
  31965. break;
  31966. }
  31967. };
  31968. /**
  31969. * Associates the vertexData to the passed Mesh.
  31970. * Sets it as updatable or not (default `false`).
  31971. * Returns the VertexData.
  31972. */
  31973. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31974. this._applyTo(mesh, updatable);
  31975. return this;
  31976. };
  31977. /**
  31978. * Associates the vertexData to the passed Geometry.
  31979. * Sets it as updatable or not (default `false`).
  31980. * Returns the VertexData.
  31981. */
  31982. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31983. this._applyTo(geometry, updatable);
  31984. return this;
  31985. };
  31986. /**
  31987. * Updates the associated mesh.
  31988. * Returns the VertexData.
  31989. */
  31990. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31991. this._update(mesh);
  31992. return this;
  31993. };
  31994. /**
  31995. * Updates the associated geometry.
  31996. * Returns the VertexData.
  31997. */
  31998. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31999. this._update(geometry);
  32000. return this;
  32001. };
  32002. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32003. if (updatable === void 0) { updatable = false; }
  32004. if (this.positions) {
  32005. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32006. }
  32007. if (this.normals) {
  32008. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32009. }
  32010. if (this.tangents) {
  32011. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32012. }
  32013. if (this.uvs) {
  32014. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32015. }
  32016. if (this.uvs2) {
  32017. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32018. }
  32019. if (this.uvs3) {
  32020. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32021. }
  32022. if (this.uvs4) {
  32023. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32024. }
  32025. if (this.uvs5) {
  32026. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32027. }
  32028. if (this.uvs6) {
  32029. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32030. }
  32031. if (this.colors) {
  32032. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32033. }
  32034. if (this.matricesIndices) {
  32035. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32036. }
  32037. if (this.matricesWeights) {
  32038. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32039. }
  32040. if (this.matricesIndicesExtra) {
  32041. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32042. }
  32043. if (this.matricesWeightsExtra) {
  32044. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32045. }
  32046. if (this.indices) {
  32047. meshOrGeometry.setIndices(this.indices, null, updatable);
  32048. }
  32049. return this;
  32050. };
  32051. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32052. if (this.positions) {
  32053. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32054. }
  32055. if (this.normals) {
  32056. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32057. }
  32058. if (this.tangents) {
  32059. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32060. }
  32061. if (this.uvs) {
  32062. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32063. }
  32064. if (this.uvs2) {
  32065. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32066. }
  32067. if (this.uvs3) {
  32068. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32069. }
  32070. if (this.uvs4) {
  32071. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32072. }
  32073. if (this.uvs5) {
  32074. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32075. }
  32076. if (this.uvs6) {
  32077. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32078. }
  32079. if (this.colors) {
  32080. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32081. }
  32082. if (this.matricesIndices) {
  32083. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32084. }
  32085. if (this.matricesWeights) {
  32086. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32087. }
  32088. if (this.matricesIndicesExtra) {
  32089. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32090. }
  32091. if (this.matricesWeightsExtra) {
  32092. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32093. }
  32094. if (this.indices) {
  32095. meshOrGeometry.setIndices(this.indices, null);
  32096. }
  32097. return this;
  32098. };
  32099. /**
  32100. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32101. * Returns the VertexData.
  32102. */
  32103. VertexData.prototype.transform = function (matrix) {
  32104. var transformed = BABYLON.Vector3.Zero();
  32105. var index;
  32106. if (this.positions) {
  32107. var position = BABYLON.Vector3.Zero();
  32108. for (index = 0; index < this.positions.length; index += 3) {
  32109. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32110. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32111. this.positions[index] = transformed.x;
  32112. this.positions[index + 1] = transformed.y;
  32113. this.positions[index + 2] = transformed.z;
  32114. }
  32115. }
  32116. if (this.normals) {
  32117. var normal = BABYLON.Vector3.Zero();
  32118. for (index = 0; index < this.normals.length; index += 3) {
  32119. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32120. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32121. this.normals[index] = transformed.x;
  32122. this.normals[index + 1] = transformed.y;
  32123. this.normals[index + 2] = transformed.z;
  32124. }
  32125. }
  32126. if (this.tangents) {
  32127. var tangent = BABYLON.Vector4.Zero();
  32128. var tangentTransformed = BABYLON.Vector4.Zero();
  32129. for (index = 0; index < this.tangents.length; index += 4) {
  32130. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32131. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32132. this.tangents[index] = tangentTransformed.x;
  32133. this.tangents[index + 1] = tangentTransformed.y;
  32134. this.tangents[index + 2] = tangentTransformed.z;
  32135. this.tangents[index + 3] = tangentTransformed.w;
  32136. }
  32137. }
  32138. return this;
  32139. };
  32140. /**
  32141. * Merges the passed VertexData into the current one.
  32142. * Returns the modified VertexData.
  32143. */
  32144. VertexData.prototype.merge = function (other) {
  32145. this._validate();
  32146. other._validate();
  32147. if (!this.normals !== !other.normals ||
  32148. !this.tangents !== !other.tangents ||
  32149. !this.uvs !== !other.uvs ||
  32150. !this.uvs2 !== !other.uvs2 ||
  32151. !this.uvs3 !== !other.uvs3 ||
  32152. !this.uvs4 !== !other.uvs4 ||
  32153. !this.uvs5 !== !other.uvs5 ||
  32154. !this.uvs6 !== !other.uvs6 ||
  32155. !this.colors !== !other.colors ||
  32156. !this.matricesIndices !== !other.matricesIndices ||
  32157. !this.matricesWeights !== !other.matricesWeights ||
  32158. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32159. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32160. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32161. }
  32162. if (other.indices) {
  32163. if (!this.indices) {
  32164. this.indices = [];
  32165. }
  32166. var offset = this.positions ? this.positions.length / 3 : 0;
  32167. for (var index = 0; index < other.indices.length; index++) {
  32168. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32169. this.indices.push(other.indices[index] + offset);
  32170. }
  32171. }
  32172. this.positions = this._mergeElement(this.positions, other.positions);
  32173. this.normals = this._mergeElement(this.normals, other.normals);
  32174. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32175. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32176. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32177. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32178. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32179. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32180. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32181. this.colors = this._mergeElement(this.colors, other.colors);
  32182. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32183. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32184. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32185. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32186. return this;
  32187. };
  32188. VertexData.prototype._mergeElement = function (source, other) {
  32189. if (!source) {
  32190. return other;
  32191. }
  32192. if (!other) {
  32193. return source;
  32194. }
  32195. var len = other.length + source.length;
  32196. var isSrcTypedArray = source instanceof Float32Array;
  32197. var isOthTypedArray = other instanceof Float32Array;
  32198. // use non-loop method when the source is Float32Array
  32199. if (isSrcTypedArray) {
  32200. var ret32 = new Float32Array(len);
  32201. ret32.set(source);
  32202. ret32.set(other, source.length);
  32203. return ret32;
  32204. // source is number[], when other is also use concat
  32205. }
  32206. else if (!isOthTypedArray) {
  32207. return source.concat(other);
  32208. // source is a number[], but other is a Float32Array, loop required
  32209. }
  32210. else {
  32211. var ret = source.slice(0); // copy source to a separate array
  32212. for (var i = 0, len = other.length; i < len; i++) {
  32213. ret.push(other[i]);
  32214. }
  32215. return ret;
  32216. }
  32217. };
  32218. VertexData.prototype._validate = function () {
  32219. if (!this.positions) {
  32220. throw new Error("Positions are required");
  32221. }
  32222. var getElementCount = function (kind, values) {
  32223. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32224. if ((values.length % stride) !== 0) {
  32225. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32226. }
  32227. return values.length / stride;
  32228. };
  32229. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32230. var validateElementCount = function (kind, values) {
  32231. var elementCount = getElementCount(kind, values);
  32232. if (elementCount !== positionsElementCount) {
  32233. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32234. }
  32235. };
  32236. if (this.normals)
  32237. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32238. if (this.tangents)
  32239. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32240. if (this.uvs)
  32241. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32242. if (this.uvs2)
  32243. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32244. if (this.uvs3)
  32245. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32246. if (this.uvs4)
  32247. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32248. if (this.uvs5)
  32249. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32250. if (this.uvs6)
  32251. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32252. if (this.colors)
  32253. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32254. if (this.matricesIndices)
  32255. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32256. if (this.matricesWeights)
  32257. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32258. if (this.matricesIndicesExtra)
  32259. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32260. if (this.matricesWeightsExtra)
  32261. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32262. };
  32263. /**
  32264. * Serializes the VertexData.
  32265. * Returns a serialized object.
  32266. */
  32267. VertexData.prototype.serialize = function () {
  32268. var serializationObject = this.serialize();
  32269. if (this.positions) {
  32270. serializationObject.positions = this.positions;
  32271. }
  32272. if (this.normals) {
  32273. serializationObject.normals = this.normals;
  32274. }
  32275. if (this.tangents) {
  32276. serializationObject.tangents = this.tangents;
  32277. }
  32278. if (this.uvs) {
  32279. serializationObject.uvs = this.uvs;
  32280. }
  32281. if (this.uvs2) {
  32282. serializationObject.uvs2 = this.uvs2;
  32283. }
  32284. if (this.uvs3) {
  32285. serializationObject.uvs3 = this.uvs3;
  32286. }
  32287. if (this.uvs4) {
  32288. serializationObject.uvs4 = this.uvs4;
  32289. }
  32290. if (this.uvs5) {
  32291. serializationObject.uvs5 = this.uvs5;
  32292. }
  32293. if (this.uvs6) {
  32294. serializationObject.uvs6 = this.uvs6;
  32295. }
  32296. if (this.colors) {
  32297. serializationObject.colors = this.colors;
  32298. }
  32299. if (this.matricesIndices) {
  32300. serializationObject.matricesIndices = this.matricesIndices;
  32301. serializationObject.matricesIndices._isExpanded = true;
  32302. }
  32303. if (this.matricesWeights) {
  32304. serializationObject.matricesWeights = this.matricesWeights;
  32305. }
  32306. if (this.matricesIndicesExtra) {
  32307. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32308. serializationObject.matricesIndicesExtra._isExpanded = true;
  32309. }
  32310. if (this.matricesWeightsExtra) {
  32311. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32312. }
  32313. serializationObject.indices = this.indices;
  32314. return serializationObject;
  32315. };
  32316. // Statics
  32317. /**
  32318. * Returns the object VertexData associated to the passed mesh.
  32319. */
  32320. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32321. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32322. };
  32323. /**
  32324. * Returns the object VertexData associated to the passed geometry.
  32325. */
  32326. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32327. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32328. };
  32329. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32330. var result = new VertexData();
  32331. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32332. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32333. }
  32334. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32335. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32336. }
  32337. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32338. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32339. }
  32340. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32341. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32342. }
  32343. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32344. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32345. }
  32346. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32347. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32348. }
  32349. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32350. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32351. }
  32352. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32353. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32354. }
  32355. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32356. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32357. }
  32358. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32359. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32360. }
  32361. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32362. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32363. }
  32364. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32365. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32366. }
  32367. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32368. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32369. }
  32370. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32371. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32372. }
  32373. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32374. return result;
  32375. };
  32376. /**
  32377. * Creates the vertexData of the Ribbon.
  32378. */
  32379. VertexData.CreateRibbon = function (options) {
  32380. var pathArray = options.pathArray;
  32381. var closeArray = options.closeArray || false;
  32382. var closePath = options.closePath || false;
  32383. var invertUV = options.invertUV || false;
  32384. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32385. var offset = options.offset || defaultOffset;
  32386. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32387. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32388. var customUV = options.uvs;
  32389. var customColors = options.colors;
  32390. var positions = [];
  32391. var indices = [];
  32392. var normals = [];
  32393. var uvs = [];
  32394. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32395. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32396. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32397. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32398. var minlg; // minimal length among all paths from pathArray
  32399. var lg = []; // array of path lengths : nb of vertex per path
  32400. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32401. var p; // path iterator
  32402. var i; // point iterator
  32403. var j; // point iterator
  32404. // if single path in pathArray
  32405. if (pathArray.length < 2) {
  32406. var ar1 = [];
  32407. var ar2 = [];
  32408. for (i = 0; i < pathArray[0].length - offset; i++) {
  32409. ar1.push(pathArray[0][i]);
  32410. ar2.push(pathArray[0][i + offset]);
  32411. }
  32412. pathArray = [ar1, ar2];
  32413. }
  32414. // positions and horizontal distances (u)
  32415. var idc = 0;
  32416. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32417. var path;
  32418. var l;
  32419. minlg = pathArray[0].length;
  32420. var vectlg;
  32421. var dist;
  32422. for (p = 0; p < pathArray.length; p++) {
  32423. uTotalDistance[p] = 0;
  32424. us[p] = [0];
  32425. path = pathArray[p];
  32426. l = path.length;
  32427. minlg = (minlg < l) ? minlg : l;
  32428. j = 0;
  32429. while (j < l) {
  32430. positions.push(path[j].x, path[j].y, path[j].z);
  32431. if (j > 0) {
  32432. vectlg = path[j].subtract(path[j - 1]).length();
  32433. dist = vectlg + uTotalDistance[p];
  32434. us[p].push(dist);
  32435. uTotalDistance[p] = dist;
  32436. }
  32437. j++;
  32438. }
  32439. if (closePath) {
  32440. j--;
  32441. positions.push(path[0].x, path[0].y, path[0].z);
  32442. vectlg = path[j].subtract(path[0]).length();
  32443. dist = vectlg + uTotalDistance[p];
  32444. us[p].push(dist);
  32445. uTotalDistance[p] = dist;
  32446. }
  32447. lg[p] = l + closePathCorr;
  32448. idx[p] = idc;
  32449. idc += (l + closePathCorr);
  32450. }
  32451. // vertical distances (v)
  32452. var path1;
  32453. var path2;
  32454. var vertex1 = null;
  32455. var vertex2 = null;
  32456. for (i = 0; i < minlg + closePathCorr; i++) {
  32457. vTotalDistance[i] = 0;
  32458. vs[i] = [0];
  32459. for (p = 0; p < pathArray.length - 1; p++) {
  32460. path1 = pathArray[p];
  32461. path2 = pathArray[p + 1];
  32462. if (i === minlg) {
  32463. vertex1 = path1[0];
  32464. vertex2 = path2[0];
  32465. }
  32466. else {
  32467. vertex1 = path1[i];
  32468. vertex2 = path2[i];
  32469. }
  32470. vectlg = vertex2.subtract(vertex1).length();
  32471. dist = vectlg + vTotalDistance[i];
  32472. vs[i].push(dist);
  32473. vTotalDistance[i] = dist;
  32474. }
  32475. if (closeArray && vertex2 && vertex1) {
  32476. path1 = pathArray[p];
  32477. path2 = pathArray[0];
  32478. if (i === minlg) {
  32479. vertex2 = path2[0];
  32480. }
  32481. vectlg = vertex2.subtract(vertex1).length();
  32482. dist = vectlg + vTotalDistance[i];
  32483. vTotalDistance[i] = dist;
  32484. }
  32485. }
  32486. // uvs
  32487. var u;
  32488. var v;
  32489. if (customUV) {
  32490. for (p = 0; p < customUV.length; p++) {
  32491. uvs.push(customUV[p].x, customUV[p].y);
  32492. }
  32493. }
  32494. else {
  32495. for (p = 0; p < pathArray.length; p++) {
  32496. for (i = 0; i < minlg + closePathCorr; i++) {
  32497. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32498. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32499. if (invertUV) {
  32500. uvs.push(v, u);
  32501. }
  32502. else {
  32503. uvs.push(u, v);
  32504. }
  32505. }
  32506. }
  32507. }
  32508. // indices
  32509. p = 0; // path index
  32510. var pi = 0; // positions array index
  32511. var l1 = lg[p] - 1; // path1 length
  32512. var l2 = lg[p + 1] - 1; // path2 length
  32513. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32514. var shft = idx[1] - idx[0]; // shift
  32515. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32516. while (pi <= min && p < path1nb) {
  32517. // 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
  32518. indices.push(pi, pi + shft, pi + 1);
  32519. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32520. pi += 1;
  32521. if (pi === min) {
  32522. p++;
  32523. if (p === lg.length - 1) {
  32524. shft = idx[0] - idx[p];
  32525. l1 = lg[p] - 1;
  32526. l2 = lg[0] - 1;
  32527. }
  32528. else {
  32529. shft = idx[p + 1] - idx[p];
  32530. l1 = lg[p] - 1;
  32531. l2 = lg[p + 1] - 1;
  32532. }
  32533. pi = idx[p];
  32534. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32535. }
  32536. }
  32537. // normals
  32538. VertexData.ComputeNormals(positions, indices, normals);
  32539. if (closePath) {
  32540. var indexFirst = 0;
  32541. var indexLast = 0;
  32542. for (p = 0; p < pathArray.length; p++) {
  32543. indexFirst = idx[p] * 3;
  32544. if (p + 1 < pathArray.length) {
  32545. indexLast = (idx[p + 1] - 1) * 3;
  32546. }
  32547. else {
  32548. indexLast = normals.length - 3;
  32549. }
  32550. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32551. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32552. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32553. normals[indexLast] = normals[indexFirst];
  32554. normals[indexLast + 1] = normals[indexFirst + 1];
  32555. normals[indexLast + 2] = normals[indexFirst + 2];
  32556. }
  32557. }
  32558. // sides
  32559. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32560. // Colors
  32561. var colors = null;
  32562. if (customColors) {
  32563. colors = new Float32Array(customColors.length * 4);
  32564. for (var c = 0; c < customColors.length; c++) {
  32565. colors[c * 4] = customColors[c].r;
  32566. colors[c * 4 + 1] = customColors[c].g;
  32567. colors[c * 4 + 2] = customColors[c].b;
  32568. colors[c * 4 + 3] = customColors[c].a;
  32569. }
  32570. }
  32571. // Result
  32572. var vertexData = new VertexData();
  32573. var positions32 = new Float32Array(positions);
  32574. var normals32 = new Float32Array(normals);
  32575. var uvs32 = new Float32Array(uvs);
  32576. vertexData.indices = indices;
  32577. vertexData.positions = positions32;
  32578. vertexData.normals = normals32;
  32579. vertexData.uvs = uvs32;
  32580. if (colors) {
  32581. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32582. }
  32583. if (closePath) {
  32584. vertexData._idx = idx;
  32585. }
  32586. return vertexData;
  32587. };
  32588. /**
  32589. * Creates the VertexData of the Box.
  32590. */
  32591. VertexData.CreateBox = function (options) {
  32592. var normalsSource = [
  32593. new BABYLON.Vector3(0, 0, 1),
  32594. new BABYLON.Vector3(0, 0, -1),
  32595. new BABYLON.Vector3(1, 0, 0),
  32596. new BABYLON.Vector3(-1, 0, 0),
  32597. new BABYLON.Vector3(0, 1, 0),
  32598. new BABYLON.Vector3(0, -1, 0)
  32599. ];
  32600. var indices = [];
  32601. var positions = [];
  32602. var normals = [];
  32603. var uvs = [];
  32604. var width = options.width || options.size || 1;
  32605. var height = options.height || options.size || 1;
  32606. var depth = options.depth || options.size || 1;
  32607. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32608. var faceUV = options.faceUV || new Array(6);
  32609. var faceColors = options.faceColors;
  32610. var colors = [];
  32611. // default face colors and UV if undefined
  32612. for (var f = 0; f < 6; f++) {
  32613. if (faceUV[f] === undefined) {
  32614. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32615. }
  32616. if (faceColors && faceColors[f] === undefined) {
  32617. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32618. }
  32619. }
  32620. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32621. // Create each face in turn.
  32622. for (var index = 0; index < normalsSource.length; index++) {
  32623. var normal = normalsSource[index];
  32624. // Get two vectors perpendicular to the face normal and to each other.
  32625. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32626. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32627. // Six indices (two triangles) per face.
  32628. var verticesLength = positions.length / 3;
  32629. indices.push(verticesLength);
  32630. indices.push(verticesLength + 1);
  32631. indices.push(verticesLength + 2);
  32632. indices.push(verticesLength);
  32633. indices.push(verticesLength + 2);
  32634. indices.push(verticesLength + 3);
  32635. // Four vertices per face.
  32636. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32637. positions.push(vertex.x, vertex.y, vertex.z);
  32638. normals.push(normal.x, normal.y, normal.z);
  32639. uvs.push(faceUV[index].z, faceUV[index].w);
  32640. if (faceColors) {
  32641. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32642. }
  32643. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32644. positions.push(vertex.x, vertex.y, vertex.z);
  32645. normals.push(normal.x, normal.y, normal.z);
  32646. uvs.push(faceUV[index].x, faceUV[index].w);
  32647. if (faceColors) {
  32648. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32649. }
  32650. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32651. positions.push(vertex.x, vertex.y, vertex.z);
  32652. normals.push(normal.x, normal.y, normal.z);
  32653. uvs.push(faceUV[index].x, faceUV[index].y);
  32654. if (faceColors) {
  32655. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32656. }
  32657. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32658. positions.push(vertex.x, vertex.y, vertex.z);
  32659. normals.push(normal.x, normal.y, normal.z);
  32660. uvs.push(faceUV[index].z, faceUV[index].y);
  32661. if (faceColors) {
  32662. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32663. }
  32664. }
  32665. // sides
  32666. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32667. // Result
  32668. var vertexData = new VertexData();
  32669. vertexData.indices = indices;
  32670. vertexData.positions = positions;
  32671. vertexData.normals = normals;
  32672. vertexData.uvs = uvs;
  32673. if (faceColors) {
  32674. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32675. vertexData.colors = totalColors;
  32676. }
  32677. return vertexData;
  32678. };
  32679. /**
  32680. * Creates the VertexData of the Sphere.
  32681. */
  32682. VertexData.CreateSphere = function (options) {
  32683. var segments = options.segments || 32;
  32684. var diameterX = options.diameterX || options.diameter || 1;
  32685. var diameterY = options.diameterY || options.diameter || 1;
  32686. var diameterZ = options.diameterZ || options.diameter || 1;
  32687. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32688. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32689. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32690. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32691. var totalZRotationSteps = 2 + segments;
  32692. var totalYRotationSteps = 2 * totalZRotationSteps;
  32693. var indices = [];
  32694. var positions = [];
  32695. var normals = [];
  32696. var uvs = [];
  32697. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32698. var normalizedZ = zRotationStep / totalZRotationSteps;
  32699. var angleZ = normalizedZ * Math.PI * slice;
  32700. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32701. var normalizedY = yRotationStep / totalYRotationSteps;
  32702. var angleY = normalizedY * Math.PI * 2 * arc;
  32703. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32704. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32705. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32706. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32707. var vertex = complete.multiply(radius);
  32708. var normal = complete.divide(radius).normalize();
  32709. positions.push(vertex.x, vertex.y, vertex.z);
  32710. normals.push(normal.x, normal.y, normal.z);
  32711. uvs.push(normalizedY, normalizedZ);
  32712. }
  32713. if (zRotationStep > 0) {
  32714. var verticesCount = positions.length / 3;
  32715. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32716. indices.push((firstIndex));
  32717. indices.push((firstIndex + 1));
  32718. indices.push(firstIndex + totalYRotationSteps + 1);
  32719. indices.push((firstIndex + totalYRotationSteps + 1));
  32720. indices.push((firstIndex + 1));
  32721. indices.push((firstIndex + totalYRotationSteps + 2));
  32722. }
  32723. }
  32724. }
  32725. // Sides
  32726. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32727. // Result
  32728. var vertexData = new VertexData();
  32729. vertexData.indices = indices;
  32730. vertexData.positions = positions;
  32731. vertexData.normals = normals;
  32732. vertexData.uvs = uvs;
  32733. return vertexData;
  32734. };
  32735. /**
  32736. * Creates the VertexData of the Cylinder or Cone.
  32737. */
  32738. VertexData.CreateCylinder = function (options) {
  32739. var height = options.height || 2;
  32740. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32741. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32742. var tessellation = options.tessellation || 24;
  32743. var subdivisions = options.subdivisions || 1;
  32744. var hasRings = options.hasRings ? true : false;
  32745. var enclose = options.enclose ? true : false;
  32746. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32747. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32748. var faceUV = options.faceUV || new Array(3);
  32749. var faceColors = options.faceColors;
  32750. // default face colors and UV if undefined
  32751. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32752. var ringNb = (hasRings) ? subdivisions : 1;
  32753. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32754. var f;
  32755. for (f = 0; f < surfaceNb; f++) {
  32756. if (faceColors && faceColors[f] === undefined) {
  32757. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32758. }
  32759. }
  32760. for (f = 0; f < surfaceNb; f++) {
  32761. if (faceUV && faceUV[f] === undefined) {
  32762. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32763. }
  32764. }
  32765. var indices = new Array();
  32766. var positions = new Array();
  32767. var normals = new Array();
  32768. var uvs = new Array();
  32769. var colors = new Array();
  32770. var angle_step = Math.PI * 2 * arc / tessellation;
  32771. var angle;
  32772. var h;
  32773. var radius;
  32774. var tan = (diameterBottom - diameterTop) / 2 / height;
  32775. var ringVertex = BABYLON.Vector3.Zero();
  32776. var ringNormal = BABYLON.Vector3.Zero();
  32777. var ringFirstVertex = BABYLON.Vector3.Zero();
  32778. var ringFirstNormal = BABYLON.Vector3.Zero();
  32779. var quadNormal = BABYLON.Vector3.Zero();
  32780. var Y = BABYLON.Axis.Y;
  32781. // positions, normals, uvs
  32782. var i;
  32783. var j;
  32784. var r;
  32785. var ringIdx = 1;
  32786. var s = 1; // surface index
  32787. var cs = 0;
  32788. var v = 0;
  32789. for (i = 0; i <= subdivisions; i++) {
  32790. h = i / subdivisions;
  32791. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32792. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32793. for (r = 0; r < ringIdx; r++) {
  32794. if (hasRings) {
  32795. s += r;
  32796. }
  32797. if (enclose) {
  32798. s += 2 * r;
  32799. }
  32800. for (j = 0; j <= tessellation; j++) {
  32801. angle = j * angle_step;
  32802. // position
  32803. ringVertex.x = Math.cos(-angle) * radius;
  32804. ringVertex.y = -height / 2 + h * height;
  32805. ringVertex.z = Math.sin(-angle) * radius;
  32806. // normal
  32807. if (diameterTop === 0 && i === subdivisions) {
  32808. // if no top cap, reuse former normals
  32809. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32810. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32811. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32812. }
  32813. else {
  32814. ringNormal.x = ringVertex.x;
  32815. ringNormal.z = ringVertex.z;
  32816. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32817. ringNormal.normalize();
  32818. }
  32819. // keep first ring vertex values for enclose
  32820. if (j === 0) {
  32821. ringFirstVertex.copyFrom(ringVertex);
  32822. ringFirstNormal.copyFrom(ringNormal);
  32823. }
  32824. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32825. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32826. if (hasRings) {
  32827. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32828. }
  32829. else {
  32830. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32831. }
  32832. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32833. if (faceColors) {
  32834. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32835. }
  32836. }
  32837. // if enclose, add four vertices and their dedicated normals
  32838. if (arc !== 1 && enclose) {
  32839. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32840. positions.push(0, ringVertex.y, 0);
  32841. positions.push(0, ringVertex.y, 0);
  32842. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32843. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32844. quadNormal.normalize();
  32845. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32846. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32847. quadNormal.normalize();
  32848. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32849. if (hasRings) {
  32850. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32851. }
  32852. else {
  32853. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32854. }
  32855. uvs.push(faceUV[s + 1].x, v);
  32856. uvs.push(faceUV[s + 1].z, v);
  32857. if (hasRings) {
  32858. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32859. }
  32860. else {
  32861. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32862. }
  32863. uvs.push(faceUV[s + 2].x, v);
  32864. uvs.push(faceUV[s + 2].z, v);
  32865. if (faceColors) {
  32866. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32867. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32868. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32869. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32870. }
  32871. }
  32872. if (cs !== s) {
  32873. cs = s;
  32874. }
  32875. }
  32876. }
  32877. // indices
  32878. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32879. var s;
  32880. i = 0;
  32881. for (s = 0; s < subdivisions; s++) {
  32882. var i0 = 0;
  32883. var i1 = 0;
  32884. var i2 = 0;
  32885. var i3 = 0;
  32886. for (j = 0; j < tessellation; j++) {
  32887. i0 = i * (e + 1) + j;
  32888. i1 = (i + 1) * (e + 1) + j;
  32889. i2 = i * (e + 1) + (j + 1);
  32890. i3 = (i + 1) * (e + 1) + (j + 1);
  32891. indices.push(i0, i1, i2);
  32892. indices.push(i3, i2, i1);
  32893. }
  32894. if (arc !== 1 && enclose) {
  32895. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32896. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32897. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32898. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32899. }
  32900. i = (hasRings) ? (i + 2) : (i + 1);
  32901. }
  32902. // Caps
  32903. var createCylinderCap = function (isTop) {
  32904. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32905. if (radius === 0) {
  32906. return;
  32907. }
  32908. // Cap positions, normals & uvs
  32909. var angle;
  32910. var circleVector;
  32911. var i;
  32912. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32913. var c = null;
  32914. if (faceColors) {
  32915. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32916. }
  32917. // cap center
  32918. var vbase = positions.length / 3;
  32919. var offset = isTop ? height / 2 : -height / 2;
  32920. var center = new BABYLON.Vector3(0, offset, 0);
  32921. positions.push(center.x, center.y, center.z);
  32922. normals.push(0, isTop ? 1 : -1, 0);
  32923. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32924. if (c) {
  32925. colors.push(c.r, c.g, c.b, c.a);
  32926. }
  32927. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32928. for (i = 0; i <= tessellation; i++) {
  32929. angle = Math.PI * 2 * i * arc / tessellation;
  32930. var cos = Math.cos(-angle);
  32931. var sin = Math.sin(-angle);
  32932. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32933. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32934. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32935. normals.push(0, isTop ? 1 : -1, 0);
  32936. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32937. if (c) {
  32938. colors.push(c.r, c.g, c.b, c.a);
  32939. }
  32940. }
  32941. // Cap indices
  32942. for (i = 0; i < tessellation; i++) {
  32943. if (!isTop) {
  32944. indices.push(vbase);
  32945. indices.push(vbase + (i + 1));
  32946. indices.push(vbase + (i + 2));
  32947. }
  32948. else {
  32949. indices.push(vbase);
  32950. indices.push(vbase + (i + 2));
  32951. indices.push(vbase + (i + 1));
  32952. }
  32953. }
  32954. };
  32955. // add caps to geometry
  32956. createCylinderCap(false);
  32957. createCylinderCap(true);
  32958. // Sides
  32959. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32960. var vertexData = new VertexData();
  32961. vertexData.indices = indices;
  32962. vertexData.positions = positions;
  32963. vertexData.normals = normals;
  32964. vertexData.uvs = uvs;
  32965. if (faceColors) {
  32966. vertexData.colors = colors;
  32967. }
  32968. return vertexData;
  32969. };
  32970. /**
  32971. * Creates the VertexData of the Torus.
  32972. */
  32973. VertexData.CreateTorus = function (options) {
  32974. var indices = [];
  32975. var positions = [];
  32976. var normals = [];
  32977. var uvs = [];
  32978. var diameter = options.diameter || 1;
  32979. var thickness = options.thickness || 0.5;
  32980. var tessellation = options.tessellation || 16;
  32981. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32982. var stride = tessellation + 1;
  32983. for (var i = 0; i <= tessellation; i++) {
  32984. var u = i / tessellation;
  32985. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32986. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32987. for (var j = 0; j <= tessellation; j++) {
  32988. var v = 1 - j / tessellation;
  32989. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32990. var dx = Math.cos(innerAngle);
  32991. var dy = Math.sin(innerAngle);
  32992. // Create a vertex.
  32993. var normal = new BABYLON.Vector3(dx, dy, 0);
  32994. var position = normal.scale(thickness / 2);
  32995. var textureCoordinate = new BABYLON.Vector2(u, v);
  32996. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32997. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32998. positions.push(position.x, position.y, position.z);
  32999. normals.push(normal.x, normal.y, normal.z);
  33000. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33001. // And create indices for two triangles.
  33002. var nextI = (i + 1) % stride;
  33003. var nextJ = (j + 1) % stride;
  33004. indices.push(i * stride + j);
  33005. indices.push(i * stride + nextJ);
  33006. indices.push(nextI * stride + j);
  33007. indices.push(i * stride + nextJ);
  33008. indices.push(nextI * stride + nextJ);
  33009. indices.push(nextI * stride + j);
  33010. }
  33011. }
  33012. // Sides
  33013. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33014. // Result
  33015. var vertexData = new VertexData();
  33016. vertexData.indices = indices;
  33017. vertexData.positions = positions;
  33018. vertexData.normals = normals;
  33019. vertexData.uvs = uvs;
  33020. return vertexData;
  33021. };
  33022. /**
  33023. * Creates the VertexData of the LineSystem.
  33024. */
  33025. VertexData.CreateLineSystem = function (options) {
  33026. var indices = [];
  33027. var positions = [];
  33028. var lines = options.lines;
  33029. var colors = options.colors;
  33030. var vertexColors = [];
  33031. var idx = 0;
  33032. for (var l = 0; l < lines.length; l++) {
  33033. var points = lines[l];
  33034. for (var index = 0; index < points.length; index++) {
  33035. positions.push(points[index].x, points[index].y, points[index].z);
  33036. if (colors) {
  33037. var color = colors[l];
  33038. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33039. }
  33040. if (index > 0) {
  33041. indices.push(idx - 1);
  33042. indices.push(idx);
  33043. }
  33044. idx++;
  33045. }
  33046. }
  33047. var vertexData = new VertexData();
  33048. vertexData.indices = indices;
  33049. vertexData.positions = positions;
  33050. if (colors) {
  33051. vertexData.colors = vertexColors;
  33052. }
  33053. return vertexData;
  33054. };
  33055. /**
  33056. * Create the VertexData of the DashedLines.
  33057. */
  33058. VertexData.CreateDashedLines = function (options) {
  33059. var dashSize = options.dashSize || 3;
  33060. var gapSize = options.gapSize || 1;
  33061. var dashNb = options.dashNb || 200;
  33062. var points = options.points;
  33063. var positions = new Array();
  33064. var indices = new Array();
  33065. var curvect = BABYLON.Vector3.Zero();
  33066. var lg = 0;
  33067. var nb = 0;
  33068. var shft = 0;
  33069. var dashshft = 0;
  33070. var curshft = 0;
  33071. var idx = 0;
  33072. var i = 0;
  33073. for (i = 0; i < points.length - 1; i++) {
  33074. points[i + 1].subtractToRef(points[i], curvect);
  33075. lg += curvect.length();
  33076. }
  33077. shft = lg / dashNb;
  33078. dashshft = dashSize * shft / (dashSize + gapSize);
  33079. for (i = 0; i < points.length - 1; i++) {
  33080. points[i + 1].subtractToRef(points[i], curvect);
  33081. nb = Math.floor(curvect.length() / shft);
  33082. curvect.normalize();
  33083. for (var j = 0; j < nb; j++) {
  33084. curshft = shft * j;
  33085. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33086. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33087. indices.push(idx, idx + 1);
  33088. idx += 2;
  33089. }
  33090. }
  33091. // Result
  33092. var vertexData = new VertexData();
  33093. vertexData.positions = positions;
  33094. vertexData.indices = indices;
  33095. return vertexData;
  33096. };
  33097. /**
  33098. * Creates the VertexData of the Ground.
  33099. */
  33100. VertexData.CreateGround = function (options) {
  33101. var indices = [];
  33102. var positions = [];
  33103. var normals = [];
  33104. var uvs = [];
  33105. var row, col;
  33106. var width = options.width || 1;
  33107. var height = options.height || 1;
  33108. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33109. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33110. for (row = 0; row <= subdivisionsY; row++) {
  33111. for (col = 0; col <= subdivisionsX; col++) {
  33112. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33113. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33114. positions.push(position.x, position.y, position.z);
  33115. normals.push(normal.x, normal.y, normal.z);
  33116. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33117. }
  33118. }
  33119. for (row = 0; row < subdivisionsY; row++) {
  33120. for (col = 0; col < subdivisionsX; col++) {
  33121. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33122. indices.push(col + 1 + row * (subdivisionsX + 1));
  33123. indices.push(col + row * (subdivisionsX + 1));
  33124. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33125. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33126. indices.push(col + row * (subdivisionsX + 1));
  33127. }
  33128. }
  33129. // Result
  33130. var vertexData = new VertexData();
  33131. vertexData.indices = indices;
  33132. vertexData.positions = positions;
  33133. vertexData.normals = normals;
  33134. vertexData.uvs = uvs;
  33135. return vertexData;
  33136. };
  33137. /**
  33138. * Creates the VertexData of the TiledGround.
  33139. */
  33140. VertexData.CreateTiledGround = function (options) {
  33141. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33142. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33143. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33144. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33145. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33146. var precision = options.precision || { w: 1, h: 1 };
  33147. var indices = new Array();
  33148. var positions = new Array();
  33149. var normals = new Array();
  33150. var uvs = new Array();
  33151. var row, col, tileRow, tileCol;
  33152. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33153. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33154. precision.w = (precision.w < 1) ? 1 : precision.w;
  33155. precision.h = (precision.h < 1) ? 1 : precision.h;
  33156. var tileSize = {
  33157. 'w': (xmax - xmin) / subdivisions.w,
  33158. 'h': (zmax - zmin) / subdivisions.h
  33159. };
  33160. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33161. // Indices
  33162. var base = positions.length / 3;
  33163. var rowLength = precision.w + 1;
  33164. for (row = 0; row < precision.h; row++) {
  33165. for (col = 0; col < precision.w; col++) {
  33166. var square = [
  33167. base + col + row * rowLength,
  33168. base + (col + 1) + row * rowLength,
  33169. base + (col + 1) + (row + 1) * rowLength,
  33170. base + col + (row + 1) * rowLength
  33171. ];
  33172. indices.push(square[1]);
  33173. indices.push(square[2]);
  33174. indices.push(square[3]);
  33175. indices.push(square[0]);
  33176. indices.push(square[1]);
  33177. indices.push(square[3]);
  33178. }
  33179. }
  33180. // Position, normals and uvs
  33181. var position = BABYLON.Vector3.Zero();
  33182. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33183. for (row = 0; row <= precision.h; row++) {
  33184. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33185. for (col = 0; col <= precision.w; col++) {
  33186. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33187. position.y = 0;
  33188. positions.push(position.x, position.y, position.z);
  33189. normals.push(normal.x, normal.y, normal.z);
  33190. uvs.push(col / precision.w, row / precision.h);
  33191. }
  33192. }
  33193. }
  33194. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33195. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33196. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33197. }
  33198. }
  33199. // Result
  33200. var vertexData = new VertexData();
  33201. vertexData.indices = indices;
  33202. vertexData.positions = positions;
  33203. vertexData.normals = normals;
  33204. vertexData.uvs = uvs;
  33205. return vertexData;
  33206. };
  33207. /**
  33208. * Creates the VertexData of the Ground designed from a heightmap.
  33209. */
  33210. VertexData.CreateGroundFromHeightMap = function (options) {
  33211. var indices = [];
  33212. var positions = [];
  33213. var normals = [];
  33214. var uvs = [];
  33215. var row, col;
  33216. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33217. // Vertices
  33218. for (row = 0; row <= options.subdivisions; row++) {
  33219. for (col = 0; col <= options.subdivisions; col++) {
  33220. 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));
  33221. // Compute height
  33222. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33223. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33224. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33225. var r = options.buffer[pos] / 255.0;
  33226. var g = options.buffer[pos + 1] / 255.0;
  33227. var b = options.buffer[pos + 2] / 255.0;
  33228. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33229. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33230. // Add vertex
  33231. positions.push(position.x, position.y, position.z);
  33232. normals.push(0, 0, 0);
  33233. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33234. }
  33235. }
  33236. // Indices
  33237. for (row = 0; row < options.subdivisions; row++) {
  33238. for (col = 0; col < options.subdivisions; col++) {
  33239. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33240. indices.push(col + 1 + row * (options.subdivisions + 1));
  33241. indices.push(col + row * (options.subdivisions + 1));
  33242. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33243. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33244. indices.push(col + row * (options.subdivisions + 1));
  33245. }
  33246. }
  33247. // Normals
  33248. VertexData.ComputeNormals(positions, indices, normals);
  33249. // Result
  33250. var vertexData = new VertexData();
  33251. vertexData.indices = indices;
  33252. vertexData.positions = positions;
  33253. vertexData.normals = normals;
  33254. vertexData.uvs = uvs;
  33255. return vertexData;
  33256. };
  33257. /**
  33258. * Creates the VertexData of the Plane.
  33259. */
  33260. VertexData.CreatePlane = function (options) {
  33261. var indices = [];
  33262. var positions = [];
  33263. var normals = [];
  33264. var uvs = [];
  33265. var width = options.width || options.size || 1;
  33266. var height = options.height || options.size || 1;
  33267. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33268. // Vertices
  33269. var halfWidth = width / 2.0;
  33270. var halfHeight = height / 2.0;
  33271. positions.push(-halfWidth, -halfHeight, 0);
  33272. normals.push(0, 0, -1.0);
  33273. uvs.push(0.0, 0.0);
  33274. positions.push(halfWidth, -halfHeight, 0);
  33275. normals.push(0, 0, -1.0);
  33276. uvs.push(1.0, 0.0);
  33277. positions.push(halfWidth, halfHeight, 0);
  33278. normals.push(0, 0, -1.0);
  33279. uvs.push(1.0, 1.0);
  33280. positions.push(-halfWidth, halfHeight, 0);
  33281. normals.push(0, 0, -1.0);
  33282. uvs.push(0.0, 1.0);
  33283. // Indices
  33284. indices.push(0);
  33285. indices.push(1);
  33286. indices.push(2);
  33287. indices.push(0);
  33288. indices.push(2);
  33289. indices.push(3);
  33290. // Sides
  33291. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33292. // Result
  33293. var vertexData = new VertexData();
  33294. vertexData.indices = indices;
  33295. vertexData.positions = positions;
  33296. vertexData.normals = normals;
  33297. vertexData.uvs = uvs;
  33298. return vertexData;
  33299. };
  33300. /**
  33301. * Creates the VertexData of the Disc or regular Polygon.
  33302. */
  33303. VertexData.CreateDisc = function (options) {
  33304. var positions = new Array();
  33305. var indices = new Array();
  33306. var normals = new Array();
  33307. var uvs = new Array();
  33308. var radius = options.radius || 0.5;
  33309. var tessellation = options.tessellation || 64;
  33310. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33311. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33312. // positions and uvs
  33313. positions.push(0, 0, 0); // disc center first
  33314. uvs.push(0.5, 0.5);
  33315. var theta = Math.PI * 2 * arc;
  33316. var step = theta / tessellation;
  33317. for (var a = 0; a < theta; a += step) {
  33318. var x = Math.cos(a);
  33319. var y = Math.sin(a);
  33320. var u = (x + 1) / 2;
  33321. var v = (1 - y) / 2;
  33322. positions.push(radius * x, radius * y, 0);
  33323. uvs.push(u, v);
  33324. }
  33325. if (arc === 1) {
  33326. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33327. uvs.push(uvs[2], uvs[3]);
  33328. }
  33329. //indices
  33330. var vertexNb = positions.length / 3;
  33331. for (var i = 1; i < vertexNb - 1; i++) {
  33332. indices.push(i + 1, 0, i);
  33333. }
  33334. // result
  33335. VertexData.ComputeNormals(positions, indices, normals);
  33336. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33337. var vertexData = new VertexData();
  33338. vertexData.indices = indices;
  33339. vertexData.positions = positions;
  33340. vertexData.normals = normals;
  33341. vertexData.uvs = uvs;
  33342. return vertexData;
  33343. };
  33344. /**
  33345. * Re-creates the VertexData of the Polygon for sideOrientation.
  33346. */
  33347. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33348. var faceUV = fUV || new Array(3);
  33349. var faceColors = fColors;
  33350. var colors = [];
  33351. // default face colors and UV if undefined
  33352. for (var f = 0; f < 3; f++) {
  33353. if (faceUV[f] === undefined) {
  33354. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33355. }
  33356. if (faceColors && faceColors[f] === undefined) {
  33357. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33358. }
  33359. }
  33360. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33361. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33362. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33363. var indices = polygon.getIndices();
  33364. // set face colours and textures
  33365. var idx = 0;
  33366. var face = 0;
  33367. for (var index = 0; index < normals.length; index += 3) {
  33368. //Edge Face no. 1
  33369. if (Math.abs(normals[index + 1]) < 0.001) {
  33370. face = 1;
  33371. }
  33372. //Top Face no. 0
  33373. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33374. face = 0;
  33375. }
  33376. //Bottom Face no. 2
  33377. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33378. face = 2;
  33379. }
  33380. idx = index / 3;
  33381. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33382. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33383. if (faceColors) {
  33384. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33385. }
  33386. }
  33387. // sides
  33388. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33389. // Result
  33390. var vertexData = new VertexData();
  33391. vertexData.indices = indices;
  33392. vertexData.positions = positions;
  33393. vertexData.normals = normals;
  33394. vertexData.uvs = uvs;
  33395. if (faceColors) {
  33396. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33397. vertexData.colors = totalColors;
  33398. }
  33399. return vertexData;
  33400. };
  33401. /**
  33402. * Creates the VertexData of the IcoSphere.
  33403. */
  33404. VertexData.CreateIcoSphere = function (options) {
  33405. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33406. var radius = options.radius || 1;
  33407. var flat = (options.flat === undefined) ? true : options.flat;
  33408. var subdivisions = options.subdivisions || 4;
  33409. var radiusX = options.radiusX || radius;
  33410. var radiusY = options.radiusY || radius;
  33411. var radiusZ = options.radiusZ || radius;
  33412. var t = (1 + Math.sqrt(5)) / 2;
  33413. // 12 vertex x,y,z
  33414. var ico_vertices = [
  33415. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33416. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33417. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33418. ];
  33419. // index of 3 vertex makes a face of icopshere
  33420. var ico_indices = [
  33421. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33422. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33423. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33424. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33425. ];
  33426. // vertex for uv have aliased position, not for UV
  33427. var vertices_unalias_id = [
  33428. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33429. // vertex alias
  33430. 0,
  33431. 2,
  33432. 3,
  33433. 3,
  33434. 3,
  33435. 4,
  33436. 7,
  33437. 8,
  33438. 9,
  33439. 9,
  33440. 10,
  33441. 11 // 23: B + 12
  33442. ];
  33443. // uv as integer step (not pixels !)
  33444. var ico_vertexuv = [
  33445. 5, 1, 3, 1, 6, 4, 0, 0,
  33446. 5, 3, 4, 2, 2, 2, 4, 0,
  33447. 2, 0, 1, 1, 6, 0, 6, 2,
  33448. // vertex alias (for same vertex on different faces)
  33449. 0, 4,
  33450. 3, 3,
  33451. 4, 4,
  33452. 3, 1,
  33453. 4, 2,
  33454. 4, 4,
  33455. 0, 2,
  33456. 1, 1,
  33457. 2, 2,
  33458. 3, 3,
  33459. 1, 3,
  33460. 2, 4 // 23: B + 12
  33461. ];
  33462. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33463. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33464. // First island of uv mapping
  33465. // v = 4h 3+ 2
  33466. // v = 3h 9+ 4
  33467. // v = 2h 9+ 5 B
  33468. // v = 1h 9 1 0
  33469. // v = 0h 3 8 7 A
  33470. // u = 0 1 2 3 4 5 6 *a
  33471. // Second island of uv mapping
  33472. // v = 4h 0+ B+ 4+
  33473. // v = 3h A+ 2+
  33474. // v = 2h 7+ 6 3+
  33475. // v = 1h 8+ 3+
  33476. // v = 0h
  33477. // u = 0 1 2 3 4 5 6 *a
  33478. // Face layout on texture UV mapping
  33479. // ============
  33480. // \ 4 /\ 16 / ======
  33481. // \ / \ / /\ 11 /
  33482. // \/ 7 \/ / \ /
  33483. // ======= / 10 \/
  33484. // /\ 17 /\ =======
  33485. // / \ / \ \ 15 /\
  33486. // / 8 \/ 12 \ \ / \
  33487. // ============ \/ 6 \
  33488. // \ 18 /\ ============
  33489. // \ / \ \ 5 /\ 0 /
  33490. // \/ 13 \ \ / \ /
  33491. // ======= \/ 1 \/
  33492. // =============
  33493. // /\ 19 /\ 2 /\
  33494. // / \ / \ / \
  33495. // / 14 \/ 9 \/ 3 \
  33496. // ===================
  33497. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33498. var ustep = 138 / 1024;
  33499. var vstep = 239 / 1024;
  33500. var uoffset = 60 / 1024;
  33501. var voffset = 26 / 1024;
  33502. // Second island should have margin, not to touch the first island
  33503. // avoid any borderline artefact in pixel rounding
  33504. var island_u_offset = -40 / 1024;
  33505. var island_v_offset = +20 / 1024;
  33506. // face is either island 0 or 1 :
  33507. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33508. var island = [
  33509. 0, 0, 0, 0, 1,
  33510. 0, 0, 1, 1, 0,
  33511. 0, 0, 1, 1, 0,
  33512. 0, 1, 1, 1, 0 // 15 - 19
  33513. ];
  33514. var indices = new Array();
  33515. var positions = new Array();
  33516. var normals = new Array();
  33517. var uvs = new Array();
  33518. var current_indice = 0;
  33519. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33520. var face_vertex_pos = new Array(3);
  33521. var face_vertex_uv = new Array(3);
  33522. var v012;
  33523. for (v012 = 0; v012 < 3; v012++) {
  33524. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33525. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33526. }
  33527. // create all with normals
  33528. for (var face = 0; face < 20; face++) {
  33529. // 3 vertex per face
  33530. for (v012 = 0; v012 < 3; v012++) {
  33531. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33532. var v_id = ico_indices[3 * face + v012];
  33533. // vertex have 3D position (x,y,z)
  33534. 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]);
  33535. // Normalize to get normal, then scale to radius
  33536. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33537. // uv Coordinates from vertex ID
  33538. 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);
  33539. }
  33540. // Subdivide the face (interpolate pos, norm, uv)
  33541. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33542. // - norm is linear interpolation of vertex corner normal
  33543. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33544. // - uv is linear interpolation
  33545. //
  33546. // Topology is as below for sub-divide by 2
  33547. // vertex shown as v0,v1,v2
  33548. // interp index is i1 to progress in range [v0,v1[
  33549. // interp index is i2 to progress in range [v0,v2[
  33550. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33551. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33552. //
  33553. //
  33554. // i2 v2
  33555. // ^ ^
  33556. // / / \
  33557. // / / \
  33558. // / / \
  33559. // / / (0,1) \
  33560. // / #---------\
  33561. // / / \ (0,0)'/ \
  33562. // / / \ / \
  33563. // / / \ / \
  33564. // / / (0,0) \ / (1,0) \
  33565. // / #---------#---------\
  33566. // v0 v1
  33567. //
  33568. // --------------------> i1
  33569. //
  33570. // interp of (i1,i2):
  33571. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33572. // along i1 : lerp(x0,x1, i1/(S-i2))
  33573. //
  33574. // centroid of triangle is needed to get help normal computation
  33575. // (c1,c2) are used for centroid location
  33576. var interp_vertex = function (i1, i2, c1, c2) {
  33577. // vertex is interpolated from
  33578. // - face_vertex_pos[0..2]
  33579. // - face_vertex_uv[0..2]
  33580. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33581. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33582. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33583. pos_interp.normalize();
  33584. var vertex_normal;
  33585. if (flat) {
  33586. // in flat mode, recalculate normal as face centroid normal
  33587. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33588. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33589. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33590. }
  33591. else {
  33592. // in smooth mode, recalculate normal from each single vertex position
  33593. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33594. }
  33595. // Vertex normal need correction due to X,Y,Z radius scaling
  33596. vertex_normal.x /= radiusX;
  33597. vertex_normal.y /= radiusY;
  33598. vertex_normal.z /= radiusZ;
  33599. vertex_normal.normalize();
  33600. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33601. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33602. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33603. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33604. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33605. uvs.push(uv_interp.x, uv_interp.y);
  33606. // push each vertex has member of a face
  33607. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33608. indices.push(current_indice);
  33609. current_indice++;
  33610. };
  33611. for (var i2 = 0; i2 < subdivisions; i2++) {
  33612. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33613. // face : (i1,i2) for /\ :
  33614. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33615. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33616. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33617. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33618. if (i1 + i2 + 1 < subdivisions) {
  33619. // face : (i1,i2)' for \/ :
  33620. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33621. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33622. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33623. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33624. }
  33625. }
  33626. }
  33627. }
  33628. // Sides
  33629. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33630. // Result
  33631. var vertexData = new VertexData();
  33632. vertexData.indices = indices;
  33633. vertexData.positions = positions;
  33634. vertexData.normals = normals;
  33635. vertexData.uvs = uvs;
  33636. return vertexData;
  33637. };
  33638. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33639. /**
  33640. * Creates the VertexData of the Polyhedron.
  33641. */
  33642. VertexData.CreatePolyhedron = function (options) {
  33643. // provided polyhedron types :
  33644. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33645. // 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)
  33646. var polyhedra = [];
  33647. 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]] };
  33648. 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]] };
  33649. polyhedra[2] = {
  33650. 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]],
  33651. 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]]
  33652. };
  33653. polyhedra[3] = {
  33654. 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]],
  33655. 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]]
  33656. };
  33657. polyhedra[4] = {
  33658. 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]],
  33659. 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]]
  33660. };
  33661. 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]] };
  33662. 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]] };
  33663. 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]] };
  33664. 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]] };
  33665. 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]] };
  33666. 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]] };
  33667. 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]] };
  33668. 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]] };
  33669. 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]] };
  33670. polyhedra[14] = {
  33671. 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]],
  33672. 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]]
  33673. };
  33674. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33675. var size = options.size;
  33676. var sizeX = options.sizeX || size || 1;
  33677. var sizeY = options.sizeY || size || 1;
  33678. var sizeZ = options.sizeZ || size || 1;
  33679. var data = options.custom || polyhedra[type];
  33680. var nbfaces = data.face.length;
  33681. var faceUV = options.faceUV || new Array(nbfaces);
  33682. var faceColors = options.faceColors;
  33683. var flat = (options.flat === undefined) ? true : options.flat;
  33684. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33685. var positions = new Array();
  33686. var indices = new Array();
  33687. var normals = new Array();
  33688. var uvs = new Array();
  33689. var colors = new Array();
  33690. var index = 0;
  33691. var faceIdx = 0; // face cursor in the array "indexes"
  33692. var indexes = new Array();
  33693. var i = 0;
  33694. var f = 0;
  33695. var u, v, ang, x, y, tmp;
  33696. // default face colors and UV if undefined
  33697. if (flat) {
  33698. for (f = 0; f < nbfaces; f++) {
  33699. if (faceColors && faceColors[f] === undefined) {
  33700. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33701. }
  33702. if (faceUV && faceUV[f] === undefined) {
  33703. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33704. }
  33705. }
  33706. }
  33707. if (!flat) {
  33708. for (i = 0; i < data.vertex.length; i++) {
  33709. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33710. uvs.push(0, 0);
  33711. }
  33712. for (f = 0; f < nbfaces; f++) {
  33713. for (i = 0; i < data.face[f].length - 2; i++) {
  33714. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33715. }
  33716. }
  33717. }
  33718. else {
  33719. for (f = 0; f < nbfaces; f++) {
  33720. var fl = data.face[f].length; // number of vertices of the current face
  33721. ang = 2 * Math.PI / fl;
  33722. x = 0.5 * Math.tan(ang / 2);
  33723. y = 0.5;
  33724. // positions, uvs, colors
  33725. for (i = 0; i < fl; i++) {
  33726. // positions
  33727. 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);
  33728. indexes.push(index);
  33729. index++;
  33730. // uvs
  33731. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33732. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33733. uvs.push(u, v);
  33734. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33735. y = x * Math.sin(ang) + y * Math.cos(ang);
  33736. x = tmp;
  33737. // colors
  33738. if (faceColors) {
  33739. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33740. }
  33741. }
  33742. // indices from indexes
  33743. for (i = 0; i < fl - 2; i++) {
  33744. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33745. }
  33746. faceIdx += fl;
  33747. }
  33748. }
  33749. VertexData.ComputeNormals(positions, indices, normals);
  33750. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33751. var vertexData = new VertexData();
  33752. vertexData.positions = positions;
  33753. vertexData.indices = indices;
  33754. vertexData.normals = normals;
  33755. vertexData.uvs = uvs;
  33756. if (faceColors && flat) {
  33757. vertexData.colors = colors;
  33758. }
  33759. return vertexData;
  33760. };
  33761. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33762. /**
  33763. * Creates the VertexData of the Torus Knot.
  33764. */
  33765. VertexData.CreateTorusKnot = function (options) {
  33766. var indices = new Array();
  33767. var positions = new Array();
  33768. var normals = new Array();
  33769. var uvs = new Array();
  33770. var radius = options.radius || 2;
  33771. var tube = options.tube || 0.5;
  33772. var radialSegments = options.radialSegments || 32;
  33773. var tubularSegments = options.tubularSegments || 32;
  33774. var p = options.p || 2;
  33775. var q = options.q || 3;
  33776. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33777. // Helper
  33778. var getPos = function (angle) {
  33779. var cu = Math.cos(angle);
  33780. var su = Math.sin(angle);
  33781. var quOverP = q / p * angle;
  33782. var cs = Math.cos(quOverP);
  33783. var tx = radius * (2 + cs) * 0.5 * cu;
  33784. var ty = radius * (2 + cs) * su * 0.5;
  33785. var tz = radius * Math.sin(quOverP) * 0.5;
  33786. return new BABYLON.Vector3(tx, ty, tz);
  33787. };
  33788. // Vertices
  33789. var i;
  33790. var j;
  33791. for (i = 0; i <= radialSegments; i++) {
  33792. var modI = i % radialSegments;
  33793. var u = modI / radialSegments * 2 * p * Math.PI;
  33794. var p1 = getPos(u);
  33795. var p2 = getPos(u + 0.01);
  33796. var tang = p2.subtract(p1);
  33797. var n = p2.add(p1);
  33798. var bitan = BABYLON.Vector3.Cross(tang, n);
  33799. n = BABYLON.Vector3.Cross(bitan, tang);
  33800. bitan.normalize();
  33801. n.normalize();
  33802. for (j = 0; j < tubularSegments; j++) {
  33803. var modJ = j % tubularSegments;
  33804. var v = modJ / tubularSegments * 2 * Math.PI;
  33805. var cx = -tube * Math.cos(v);
  33806. var cy = tube * Math.sin(v);
  33807. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33808. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33809. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33810. uvs.push(i / radialSegments);
  33811. uvs.push(j / tubularSegments);
  33812. }
  33813. }
  33814. for (i = 0; i < radialSegments; i++) {
  33815. for (j = 0; j < tubularSegments; j++) {
  33816. var jNext = (j + 1) % tubularSegments;
  33817. var a = i * tubularSegments + j;
  33818. var b = (i + 1) * tubularSegments + j;
  33819. var c = (i + 1) * tubularSegments + jNext;
  33820. var d = i * tubularSegments + jNext;
  33821. indices.push(d);
  33822. indices.push(b);
  33823. indices.push(a);
  33824. indices.push(d);
  33825. indices.push(c);
  33826. indices.push(b);
  33827. }
  33828. }
  33829. // Normals
  33830. VertexData.ComputeNormals(positions, indices, normals);
  33831. // Sides
  33832. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33833. // Result
  33834. var vertexData = new VertexData();
  33835. vertexData.indices = indices;
  33836. vertexData.positions = positions;
  33837. vertexData.normals = normals;
  33838. vertexData.uvs = uvs;
  33839. return vertexData;
  33840. };
  33841. // Tools
  33842. /**
  33843. * @param {any} - positions (number[] or Float32Array)
  33844. * @param {any} - indices (number[] or Uint16Array)
  33845. * @param {any} - normals (number[] or Float32Array)
  33846. * options (optional) :
  33847. * facetPositions : optional array of facet positions (vector3)
  33848. * facetNormals : optional array of facet normals (vector3)
  33849. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  33850. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  33851. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  33852. * bbSize : optional bounding box size data, required for facetPartitioning computation
  33853. * bInfo : optional bounding info, required for facetPartitioning computation
  33854. * useRightHandedSystem: optional boolean to for right handed system computation
  33855. * depthSort : optional boolean to enable the facet depth sort computation
  33856. * distanceTo : optional Vector3 to compute the facet depth from this location
  33857. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  33858. */
  33859. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  33860. // temporary scalar variables
  33861. var index = 0; // facet index
  33862. var p1p2x = 0.0; // p1p2 vector x coordinate
  33863. var p1p2y = 0.0; // p1p2 vector y coordinate
  33864. var p1p2z = 0.0; // p1p2 vector z coordinate
  33865. var p3p2x = 0.0; // p3p2 vector x coordinate
  33866. var p3p2y = 0.0; // p3p2 vector y coordinate
  33867. var p3p2z = 0.0; // p3p2 vector z coordinate
  33868. var faceNormalx = 0.0; // facet normal x coordinate
  33869. var faceNormaly = 0.0; // facet normal y coordinate
  33870. var faceNormalz = 0.0; // facet normal z coordinate
  33871. var length = 0.0; // facet normal length before normalization
  33872. var v1x = 0; // vector1 x index in the positions array
  33873. var v1y = 0; // vector1 y index in the positions array
  33874. var v1z = 0; // vector1 z index in the positions array
  33875. var v2x = 0; // vector2 x index in the positions array
  33876. var v2y = 0; // vector2 y index in the positions array
  33877. var v2z = 0; // vector2 z index in the positions array
  33878. var v3x = 0; // vector3 x index in the positions array
  33879. var v3y = 0; // vector3 y index in the positions array
  33880. var v3z = 0; // vector3 z index in the positions array
  33881. var computeFacetNormals = false;
  33882. var computeFacetPositions = false;
  33883. var computeFacetPartitioning = false;
  33884. var computeDepthSort = false;
  33885. var faceNormalSign = 1;
  33886. var ratio = 0;
  33887. var distanceTo = null;
  33888. if (options) {
  33889. computeFacetNormals = (options.facetNormals) ? true : false;
  33890. computeFacetPositions = (options.facetPositions) ? true : false;
  33891. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  33892. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  33893. ratio = options.ratio || 0;
  33894. computeDepthSort = (options.depthSort) ? true : false;
  33895. distanceTo = (options.distanceTo);
  33896. if (computeDepthSort) {
  33897. if (distanceTo === undefined) {
  33898. distanceTo = BABYLON.Vector3.Zero();
  33899. }
  33900. var depthSortedFacets = options.depthSortedFacets;
  33901. }
  33902. }
  33903. // facetPartitioning reinit if needed
  33904. var xSubRatio = 0;
  33905. var ySubRatio = 0;
  33906. var zSubRatio = 0;
  33907. var subSq = 0;
  33908. if (computeFacetPartitioning && options && options.bbSize) {
  33909. var ox = 0; // X partitioning index for facet position
  33910. var oy = 0; // Y partinioning index for facet position
  33911. var oz = 0; // Z partinioning index for facet position
  33912. var b1x = 0; // X partitioning index for facet v1 vertex
  33913. var b1y = 0; // Y partitioning index for facet v1 vertex
  33914. var b1z = 0; // z partitioning index for facet v1 vertex
  33915. var b2x = 0; // X partitioning index for facet v2 vertex
  33916. var b2y = 0; // Y partitioning index for facet v2 vertex
  33917. var b2z = 0; // Z partitioning index for facet v2 vertex
  33918. var b3x = 0; // X partitioning index for facet v3 vertex
  33919. var b3y = 0; // Y partitioning index for facet v3 vertex
  33920. var b3z = 0; // Z partitioning index for facet v3 vertex
  33921. var block_idx_o = 0; // facet barycenter block index
  33922. var block_idx_v1 = 0; // v1 vertex block index
  33923. var block_idx_v2 = 0; // v2 vertex block index
  33924. var block_idx_v3 = 0; // v3 vertex block index
  33925. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  33926. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  33927. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  33928. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  33929. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  33930. subSq = options.subDiv.max * options.subDiv.max;
  33931. options.facetPartitioning.length = 0;
  33932. }
  33933. // reset the normals
  33934. for (index = 0; index < positions.length; index++) {
  33935. normals[index] = 0.0;
  33936. }
  33937. // Loop : 1 indice triplet = 1 facet
  33938. var nbFaces = (indices.length / 3) | 0;
  33939. for (index = 0; index < nbFaces; index++) {
  33940. // get the indexes of the coordinates of each vertex of the facet
  33941. v1x = indices[index * 3] * 3;
  33942. v1y = v1x + 1;
  33943. v1z = v1x + 2;
  33944. v2x = indices[index * 3 + 1] * 3;
  33945. v2y = v2x + 1;
  33946. v2z = v2x + 2;
  33947. v3x = indices[index * 3 + 2] * 3;
  33948. v3y = v3x + 1;
  33949. v3z = v3x + 2;
  33950. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  33951. p1p2y = positions[v1y] - positions[v2y];
  33952. p1p2z = positions[v1z] - positions[v2z];
  33953. p3p2x = positions[v3x] - positions[v2x];
  33954. p3p2y = positions[v3y] - positions[v2y];
  33955. p3p2z = positions[v3z] - positions[v2z];
  33956. // compute the face normal with the cross product
  33957. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  33958. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  33959. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  33960. // normalize this normal and store it in the array facetData
  33961. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33962. length = (length === 0) ? 1.0 : length;
  33963. faceNormalx /= length;
  33964. faceNormaly /= length;
  33965. faceNormalz /= length;
  33966. if (computeFacetNormals && options) {
  33967. options.facetNormals[index].x = faceNormalx;
  33968. options.facetNormals[index].y = faceNormaly;
  33969. options.facetNormals[index].z = faceNormalz;
  33970. }
  33971. if (computeFacetPositions && options) {
  33972. // compute and the facet barycenter coordinates in the array facetPositions
  33973. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  33974. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  33975. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  33976. }
  33977. if (computeFacetPartitioning && options) {
  33978. // store the facet indexes in arrays in the main facetPartitioning array :
  33979. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  33980. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  33981. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  33982. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  33983. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33984. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33985. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33986. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33987. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33988. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33989. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33990. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33991. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33992. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  33993. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  33994. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  33995. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  33996. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  33997. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  33998. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  33999. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34000. // push each facet index in each block containing the vertex
  34001. options.facetPartitioning[block_idx_v1].push(index);
  34002. if (block_idx_v2 != block_idx_v1) {
  34003. options.facetPartitioning[block_idx_v2].push(index);
  34004. }
  34005. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34006. options.facetPartitioning[block_idx_v3].push(index);
  34007. }
  34008. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34009. options.facetPartitioning[block_idx_o].push(index);
  34010. }
  34011. }
  34012. if (computeDepthSort && options && options.facetPositions) {
  34013. var dsf = depthSortedFacets[index];
  34014. dsf.ind = index * 3;
  34015. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34016. }
  34017. // compute the normals anyway
  34018. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34019. normals[v1y] += faceNormaly;
  34020. normals[v1z] += faceNormalz;
  34021. normals[v2x] += faceNormalx;
  34022. normals[v2y] += faceNormaly;
  34023. normals[v2z] += faceNormalz;
  34024. normals[v3x] += faceNormalx;
  34025. normals[v3y] += faceNormaly;
  34026. normals[v3z] += faceNormalz;
  34027. }
  34028. // last normalization of each normal
  34029. for (index = 0; index < normals.length / 3; index++) {
  34030. faceNormalx = normals[index * 3];
  34031. faceNormaly = normals[index * 3 + 1];
  34032. faceNormalz = normals[index * 3 + 2];
  34033. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34034. length = (length === 0) ? 1.0 : length;
  34035. faceNormalx /= length;
  34036. faceNormaly /= length;
  34037. faceNormalz /= length;
  34038. normals[index * 3] = faceNormalx;
  34039. normals[index * 3 + 1] = faceNormaly;
  34040. normals[index * 3 + 2] = faceNormalz;
  34041. }
  34042. };
  34043. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34044. var li = indices.length;
  34045. var ln = normals.length;
  34046. var i;
  34047. var n;
  34048. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34049. switch (sideOrientation) {
  34050. case BABYLON.Mesh.FRONTSIDE:
  34051. // nothing changed
  34052. break;
  34053. case BABYLON.Mesh.BACKSIDE:
  34054. var tmp;
  34055. // indices
  34056. for (i = 0; i < li; i += 3) {
  34057. tmp = indices[i];
  34058. indices[i] = indices[i + 2];
  34059. indices[i + 2] = tmp;
  34060. }
  34061. // normals
  34062. for (n = 0; n < ln; n++) {
  34063. normals[n] = -normals[n];
  34064. }
  34065. break;
  34066. case BABYLON.Mesh.DOUBLESIDE:
  34067. // positions
  34068. var lp = positions.length;
  34069. var l = lp / 3;
  34070. for (var p = 0; p < lp; p++) {
  34071. positions[lp + p] = positions[p];
  34072. }
  34073. // indices
  34074. for (i = 0; i < li; i += 3) {
  34075. indices[i + li] = indices[i + 2] + l;
  34076. indices[i + 1 + li] = indices[i + 1] + l;
  34077. indices[i + 2 + li] = indices[i] + l;
  34078. }
  34079. // normals
  34080. for (n = 0; n < ln; n++) {
  34081. normals[ln + n] = -normals[n];
  34082. }
  34083. // uvs
  34084. var lu = uvs.length;
  34085. var u = 0;
  34086. for (u = 0; u < lu; u++) {
  34087. uvs[u + lu] = uvs[u];
  34088. }
  34089. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34090. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34091. u = 0;
  34092. for (i = 0; i < lu / 2; i++) {
  34093. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34094. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34095. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34096. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34097. u += 2;
  34098. }
  34099. break;
  34100. }
  34101. };
  34102. /**
  34103. * Creates a new VertexData from the imported parameters.
  34104. */
  34105. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34106. var vertexData = new VertexData();
  34107. // positions
  34108. var positions = parsedVertexData.positions;
  34109. if (positions) {
  34110. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34111. }
  34112. // normals
  34113. var normals = parsedVertexData.normals;
  34114. if (normals) {
  34115. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34116. }
  34117. // tangents
  34118. var tangents = parsedVertexData.tangents;
  34119. if (tangents) {
  34120. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34121. }
  34122. // uvs
  34123. var uvs = parsedVertexData.uvs;
  34124. if (uvs) {
  34125. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34126. }
  34127. // uv2s
  34128. var uv2s = parsedVertexData.uv2s;
  34129. if (uv2s) {
  34130. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34131. }
  34132. // uv3s
  34133. var uv3s = parsedVertexData.uv3s;
  34134. if (uv3s) {
  34135. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34136. }
  34137. // uv4s
  34138. var uv4s = parsedVertexData.uv4s;
  34139. if (uv4s) {
  34140. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34141. }
  34142. // uv5s
  34143. var uv5s = parsedVertexData.uv5s;
  34144. if (uv5s) {
  34145. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34146. }
  34147. // uv6s
  34148. var uv6s = parsedVertexData.uv6s;
  34149. if (uv6s) {
  34150. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34151. }
  34152. // colors
  34153. var colors = parsedVertexData.colors;
  34154. if (colors) {
  34155. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34156. }
  34157. // matricesIndices
  34158. var matricesIndices = parsedVertexData.matricesIndices;
  34159. if (matricesIndices) {
  34160. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34161. }
  34162. // matricesWeights
  34163. var matricesWeights = parsedVertexData.matricesWeights;
  34164. if (matricesWeights) {
  34165. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34166. }
  34167. // indices
  34168. var indices = parsedVertexData.indices;
  34169. if (indices) {
  34170. vertexData.indices = indices;
  34171. }
  34172. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34173. };
  34174. return VertexData;
  34175. }());
  34176. BABYLON.VertexData = VertexData;
  34177. })(BABYLON || (BABYLON = {}));
  34178. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34179. var BABYLON;
  34180. (function (BABYLON) {
  34181. /**
  34182. * Class used to store geometry data (vertex buffers + index buffer)
  34183. */
  34184. var Geometry = /** @class */ (function () {
  34185. /**
  34186. * Creates a new geometry
  34187. * @param id defines the unique ID
  34188. * @param scene defines the hosting scene
  34189. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34190. * @param updatable defines if geometry must be updatable (false by default)
  34191. * @param mesh defines the mesh that will be associated with the geometry
  34192. */
  34193. function Geometry(id, scene, vertexData, updatable, mesh) {
  34194. if (updatable === void 0) { updatable = false; }
  34195. if (mesh === void 0) { mesh = null; }
  34196. /**
  34197. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34198. */
  34199. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34200. this._totalVertices = 0;
  34201. this._isDisposed = false;
  34202. this._indexBufferIsUpdatable = false;
  34203. this.id = id;
  34204. this._engine = scene.getEngine();
  34205. this._meshes = [];
  34206. this._scene = scene;
  34207. //Init vertex buffer cache
  34208. this._vertexBuffers = {};
  34209. this._indices = [];
  34210. this._updatable = updatable;
  34211. // vertexData
  34212. if (vertexData) {
  34213. this.setAllVerticesData(vertexData, updatable);
  34214. }
  34215. else {
  34216. this._totalVertices = 0;
  34217. this._indices = [];
  34218. }
  34219. if (this._engine.getCaps().vertexArrayObject) {
  34220. this._vertexArrayObjects = {};
  34221. }
  34222. // applyToMesh
  34223. if (mesh) {
  34224. if (mesh.getClassName() === "LinesMesh") {
  34225. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34226. this.updateExtend();
  34227. }
  34228. this.applyToMesh(mesh);
  34229. mesh.computeWorldMatrix(true);
  34230. }
  34231. }
  34232. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34233. /**
  34234. * 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
  34235. */
  34236. get: function () {
  34237. return this._boundingBias;
  34238. },
  34239. /**
  34240. * 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
  34241. */
  34242. set: function (value) {
  34243. if (this._boundingBias && this._boundingBias.equals(value)) {
  34244. return;
  34245. }
  34246. this._boundingBias = value.clone();
  34247. this.updateBoundingInfo(true, null);
  34248. },
  34249. enumerable: true,
  34250. configurable: true
  34251. });
  34252. /**
  34253. * Static function used to attach a new empty geometry to a mesh
  34254. * @param mesh defines the mesh to attach the geometry to
  34255. * @returns the new {BABYLON.Geometry}
  34256. */
  34257. Geometry.CreateGeometryForMesh = function (mesh) {
  34258. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34259. geometry.applyToMesh(mesh);
  34260. return geometry;
  34261. };
  34262. Object.defineProperty(Geometry.prototype, "extend", {
  34263. /**
  34264. * Gets the current extend of the geometry
  34265. */
  34266. get: function () {
  34267. return this._extend;
  34268. },
  34269. enumerable: true,
  34270. configurable: true
  34271. });
  34272. /**
  34273. * Gets the hosting scene
  34274. * @returns the hosting {BABYLON.Scene}
  34275. */
  34276. Geometry.prototype.getScene = function () {
  34277. return this._scene;
  34278. };
  34279. /**
  34280. * Gets the hosting engine
  34281. * @returns the hosting {BABYLON.Engine}
  34282. */
  34283. Geometry.prototype.getEngine = function () {
  34284. return this._engine;
  34285. };
  34286. /**
  34287. * Defines if the geometry is ready to use
  34288. * @returns true if the geometry is ready to be used
  34289. */
  34290. Geometry.prototype.isReady = function () {
  34291. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34292. };
  34293. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34294. /**
  34295. * Gets a value indicating that the geometry should not be serialized
  34296. */
  34297. get: function () {
  34298. for (var index = 0; index < this._meshes.length; index++) {
  34299. if (!this._meshes[index].doNotSerialize) {
  34300. return false;
  34301. }
  34302. }
  34303. return true;
  34304. },
  34305. enumerable: true,
  34306. configurable: true
  34307. });
  34308. /** @ignore */
  34309. Geometry.prototype._rebuild = function () {
  34310. if (this._vertexArrayObjects) {
  34311. this._vertexArrayObjects = {};
  34312. }
  34313. // Index buffer
  34314. if (this._meshes.length !== 0 && this._indices) {
  34315. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34316. }
  34317. // Vertex buffers
  34318. for (var key in this._vertexBuffers) {
  34319. var vertexBuffer = this._vertexBuffers[key];
  34320. vertexBuffer._rebuild();
  34321. }
  34322. };
  34323. /**
  34324. * Affects all gemetry data in one call
  34325. * @param vertexData defines the geometry data
  34326. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34327. */
  34328. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34329. vertexData.applyToGeometry(this, updatable);
  34330. this.notifyUpdate();
  34331. };
  34332. /**
  34333. * Set specific vertex data
  34334. * @param kind defines the data kind (Position, normal, etc...)
  34335. * @param data defines the vertex data to use
  34336. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34337. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34338. */
  34339. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34340. if (updatable === void 0) { updatable = false; }
  34341. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34342. this.setVerticesBuffer(buffer);
  34343. };
  34344. /**
  34345. * Removes a specific vertex data
  34346. * @param kind defines the data kind (Position, normal, etc...)
  34347. */
  34348. Geometry.prototype.removeVerticesData = function (kind) {
  34349. if (this._vertexBuffers[kind]) {
  34350. this._vertexBuffers[kind].dispose();
  34351. delete this._vertexBuffers[kind];
  34352. }
  34353. };
  34354. /**
  34355. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34356. * @param buffer defines the vertex buffer to use
  34357. */
  34358. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34359. var kind = buffer.getKind();
  34360. if (this._vertexBuffers[kind]) {
  34361. this._vertexBuffers[kind].dispose();
  34362. }
  34363. this._vertexBuffers[kind] = buffer;
  34364. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34365. var data = buffer.getData();
  34366. var stride = buffer.getStrideSize();
  34367. this._totalVertices = data.length / stride;
  34368. this.updateExtend(data, stride);
  34369. this._resetPointsArrayCache();
  34370. var meshes = this._meshes;
  34371. var numOfMeshes = meshes.length;
  34372. for (var index = 0; index < numOfMeshes; index++) {
  34373. var mesh = meshes[index];
  34374. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34375. mesh._createGlobalSubMesh(false);
  34376. mesh.computeWorldMatrix(true);
  34377. }
  34378. }
  34379. this.notifyUpdate(kind);
  34380. if (this._vertexArrayObjects) {
  34381. this._disposeVertexArrayObjects();
  34382. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34383. }
  34384. };
  34385. /**
  34386. * Update a specific vertex buffer
  34387. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34388. * It will do nothing if the buffer is not updatable
  34389. * @param kind defines the data kind (Position, normal, etc...)
  34390. * @param data defines the data to use
  34391. * @param offset defines the offset in the target buffer where to store the data
  34392. */
  34393. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34394. var vertexBuffer = this.getVertexBuffer(kind);
  34395. if (!vertexBuffer) {
  34396. return;
  34397. }
  34398. vertexBuffer.updateDirectly(data, offset);
  34399. this.notifyUpdate(kind);
  34400. };
  34401. /**
  34402. * Update a specific vertex buffer
  34403. * This function will create a new buffer if the current one is not updatable
  34404. * @param kind defines the data kind (Position, normal, etc...)
  34405. * @param data defines the data to use
  34406. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34407. */
  34408. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34409. if (updateExtends === void 0) { updateExtends = false; }
  34410. var vertexBuffer = this.getVertexBuffer(kind);
  34411. if (!vertexBuffer) {
  34412. return;
  34413. }
  34414. vertexBuffer.update(data);
  34415. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34416. var stride = vertexBuffer.getStrideSize();
  34417. this._totalVertices = data.length / stride;
  34418. this.updateBoundingInfo(updateExtends, data);
  34419. }
  34420. this.notifyUpdate(kind);
  34421. };
  34422. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34423. if (updateExtends) {
  34424. this.updateExtend(data);
  34425. }
  34426. var meshes = this._meshes;
  34427. var numOfMeshes = meshes.length;
  34428. this._resetPointsArrayCache();
  34429. for (var index = 0; index < numOfMeshes; index++) {
  34430. var mesh = meshes[index];
  34431. if (updateExtends) {
  34432. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34433. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34434. var subMesh = mesh.subMeshes[subIndex];
  34435. subMesh.refreshBoundingInfo();
  34436. }
  34437. }
  34438. }
  34439. };
  34440. /** @ignore */
  34441. Geometry.prototype._bind = function (effect, indexToBind) {
  34442. if (!effect) {
  34443. return;
  34444. }
  34445. if (indexToBind === undefined) {
  34446. indexToBind = this._indexBuffer;
  34447. }
  34448. var vbs = this.getVertexBuffers();
  34449. if (!vbs) {
  34450. return;
  34451. }
  34452. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34453. this._engine.bindBuffers(vbs, indexToBind, effect);
  34454. return;
  34455. }
  34456. // Using VAO
  34457. if (!this._vertexArrayObjects[effect.key]) {
  34458. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34459. }
  34460. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34461. };
  34462. /**
  34463. * Gets total number of vertices
  34464. * @returns the total number of vertices
  34465. */
  34466. Geometry.prototype.getTotalVertices = function () {
  34467. if (!this.isReady()) {
  34468. return 0;
  34469. }
  34470. return this._totalVertices;
  34471. };
  34472. /**
  34473. * Gets a specific vertex data attached to this geometry
  34474. * @param kind defines the data kind (Position, normal, etc...)
  34475. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34476. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34477. * @returns a float array containing vertex data
  34478. */
  34479. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34480. var vertexBuffer = this.getVertexBuffer(kind);
  34481. if (!vertexBuffer) {
  34482. return null;
  34483. }
  34484. var orig = vertexBuffer.getData();
  34485. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34486. return orig;
  34487. }
  34488. else {
  34489. var len = orig.length;
  34490. var copy = [];
  34491. for (var i = 0; i < len; i++) {
  34492. copy.push(orig[i]);
  34493. }
  34494. return copy;
  34495. }
  34496. };
  34497. /**
  34498. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34499. * @param kind defines the data kind (Position, normal, etc...)
  34500. * @returns true if the vertex buffer with the specified kind is updatable
  34501. */
  34502. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34503. var vb = this._vertexBuffers[kind];
  34504. if (!vb) {
  34505. return false;
  34506. }
  34507. return vb.isUpdatable();
  34508. };
  34509. /**
  34510. * Gets a specific vertex buffer
  34511. * @param kind defines the data kind (Position, normal, etc...)
  34512. * @returns a {BABYLON.VertexBuffer}
  34513. */
  34514. Geometry.prototype.getVertexBuffer = function (kind) {
  34515. if (!this.isReady()) {
  34516. return null;
  34517. }
  34518. return this._vertexBuffers[kind];
  34519. };
  34520. /**
  34521. * Returns all vertex buffers
  34522. * @return an object holding all vertex buffers indexed by kind
  34523. */
  34524. Geometry.prototype.getVertexBuffers = function () {
  34525. if (!this.isReady()) {
  34526. return null;
  34527. }
  34528. return this._vertexBuffers;
  34529. };
  34530. /**
  34531. * Gets a boolean indicating if specific vertex buffer is present
  34532. * @param kind defines the data kind (Position, normal, etc...)
  34533. * @returns true if data is present
  34534. */
  34535. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34536. if (!this._vertexBuffers) {
  34537. if (this._delayInfo) {
  34538. return this._delayInfo.indexOf(kind) !== -1;
  34539. }
  34540. return false;
  34541. }
  34542. return this._vertexBuffers[kind] !== undefined;
  34543. };
  34544. /**
  34545. * Gets a list of all attached data kinds (Position, normal, etc...)
  34546. * @returns a list of string containing all kinds
  34547. */
  34548. Geometry.prototype.getVerticesDataKinds = function () {
  34549. var result = [];
  34550. var kind;
  34551. if (!this._vertexBuffers && this._delayInfo) {
  34552. for (kind in this._delayInfo) {
  34553. result.push(kind);
  34554. }
  34555. }
  34556. else {
  34557. for (kind in this._vertexBuffers) {
  34558. result.push(kind);
  34559. }
  34560. }
  34561. return result;
  34562. };
  34563. /**
  34564. * Update index buffer
  34565. * @param indices defines the indices to store in the index buffer
  34566. * @param offset defines the offset in the target buffer where to store the data
  34567. */
  34568. Geometry.prototype.updateIndices = function (indices, offset) {
  34569. if (!this._indexBuffer) {
  34570. return;
  34571. }
  34572. if (!this._indexBufferIsUpdatable) {
  34573. this.setIndices(indices, null, true);
  34574. }
  34575. else {
  34576. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34577. }
  34578. };
  34579. /**
  34580. * Creates a new index buffer
  34581. * @param indices defines the indices to store in the index buffer
  34582. * @param totalVertices defines the total number of vertices (could be null)
  34583. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34584. */
  34585. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34586. if (totalVertices === void 0) { totalVertices = null; }
  34587. if (updatable === void 0) { updatable = false; }
  34588. if (this._indexBuffer) {
  34589. this._engine._releaseBuffer(this._indexBuffer);
  34590. }
  34591. this._disposeVertexArrayObjects();
  34592. this._indices = indices;
  34593. this._indexBufferIsUpdatable = updatable;
  34594. if (this._meshes.length !== 0 && this._indices) {
  34595. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34596. }
  34597. if (totalVertices != undefined) {
  34598. this._totalVertices = totalVertices;
  34599. }
  34600. var meshes = this._meshes;
  34601. var numOfMeshes = meshes.length;
  34602. for (var index = 0; index < numOfMeshes; index++) {
  34603. meshes[index]._createGlobalSubMesh(true);
  34604. }
  34605. this.notifyUpdate();
  34606. };
  34607. /**
  34608. * Return the total number of indices
  34609. * @returns the total number of indices
  34610. */
  34611. Geometry.prototype.getTotalIndices = function () {
  34612. if (!this.isReady()) {
  34613. return 0;
  34614. }
  34615. return this._indices.length;
  34616. };
  34617. /**
  34618. * Gets the index buffer array
  34619. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34620. * @returns the index buffer array
  34621. */
  34622. Geometry.prototype.getIndices = function (copyWhenShared) {
  34623. if (!this.isReady()) {
  34624. return null;
  34625. }
  34626. var orig = this._indices;
  34627. if (!copyWhenShared || this._meshes.length === 1) {
  34628. return orig;
  34629. }
  34630. else {
  34631. var len = orig.length;
  34632. var copy = [];
  34633. for (var i = 0; i < len; i++) {
  34634. copy.push(orig[i]);
  34635. }
  34636. return copy;
  34637. }
  34638. };
  34639. /**
  34640. * Gets the index buffer
  34641. * @return the index buffer
  34642. */
  34643. Geometry.prototype.getIndexBuffer = function () {
  34644. if (!this.isReady()) {
  34645. return null;
  34646. }
  34647. return this._indexBuffer;
  34648. };
  34649. /** @ignore */
  34650. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34651. if (effect === void 0) { effect = null; }
  34652. if (!effect || !this._vertexArrayObjects) {
  34653. return;
  34654. }
  34655. if (this._vertexArrayObjects[effect.key]) {
  34656. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34657. delete this._vertexArrayObjects[effect.key];
  34658. }
  34659. };
  34660. /**
  34661. * Release the associated resources for a specific mesh
  34662. * @param mesh defines the source mesh
  34663. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34664. */
  34665. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34666. var meshes = this._meshes;
  34667. var index = meshes.indexOf(mesh);
  34668. if (index === -1) {
  34669. return;
  34670. }
  34671. meshes.splice(index, 1);
  34672. mesh._geometry = null;
  34673. if (meshes.length === 0 && shouldDispose) {
  34674. this.dispose();
  34675. }
  34676. };
  34677. /**
  34678. * Apply current geometry to a given mesh
  34679. * @param mesh defines the mesh to apply geometry to
  34680. */
  34681. Geometry.prototype.applyToMesh = function (mesh) {
  34682. if (mesh._geometry === this) {
  34683. return;
  34684. }
  34685. var previousGeometry = mesh._geometry;
  34686. if (previousGeometry) {
  34687. previousGeometry.releaseForMesh(mesh);
  34688. }
  34689. var meshes = this._meshes;
  34690. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34691. mesh._geometry = this;
  34692. this._scene.pushGeometry(this);
  34693. meshes.push(mesh);
  34694. if (this.isReady()) {
  34695. this._applyToMesh(mesh);
  34696. }
  34697. else {
  34698. mesh._boundingInfo = this._boundingInfo;
  34699. }
  34700. };
  34701. Geometry.prototype.updateExtend = function (data, stride) {
  34702. if (data === void 0) { data = null; }
  34703. if (!data) {
  34704. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34705. }
  34706. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34707. };
  34708. Geometry.prototype._applyToMesh = function (mesh) {
  34709. var numOfMeshes = this._meshes.length;
  34710. // vertexBuffers
  34711. for (var kind in this._vertexBuffers) {
  34712. if (numOfMeshes === 1) {
  34713. this._vertexBuffers[kind].create();
  34714. }
  34715. var buffer = this._vertexBuffers[kind].getBuffer();
  34716. if (buffer)
  34717. buffer.references = numOfMeshes;
  34718. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34719. if (!this._extend) {
  34720. this.updateExtend(this._vertexBuffers[kind].getData());
  34721. }
  34722. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34723. mesh._createGlobalSubMesh(false);
  34724. //bounding info was just created again, world matrix should be applied again.
  34725. mesh._updateBoundingInfo();
  34726. }
  34727. }
  34728. // indexBuffer
  34729. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34730. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34731. }
  34732. if (this._indexBuffer) {
  34733. this._indexBuffer.references = numOfMeshes;
  34734. }
  34735. };
  34736. Geometry.prototype.notifyUpdate = function (kind) {
  34737. if (this.onGeometryUpdated) {
  34738. this.onGeometryUpdated(this, kind);
  34739. }
  34740. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  34741. var mesh = _a[_i];
  34742. mesh._markSubMeshesAsAttributesDirty();
  34743. }
  34744. };
  34745. /**
  34746. * Load the geometry if it was flagged as delay loaded
  34747. * @param scene defines the hosting scene
  34748. * @param onLoaded defines a callback called when the geometry is loaded
  34749. */
  34750. Geometry.prototype.load = function (scene, onLoaded) {
  34751. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34752. return;
  34753. }
  34754. if (this.isReady()) {
  34755. if (onLoaded) {
  34756. onLoaded();
  34757. }
  34758. return;
  34759. }
  34760. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34761. this._queueLoad(scene, onLoaded);
  34762. };
  34763. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34764. var _this = this;
  34765. if (!this.delayLoadingFile) {
  34766. return;
  34767. }
  34768. scene._addPendingData(this);
  34769. scene._loadFile(this.delayLoadingFile, function (data) {
  34770. if (!_this._delayLoadingFunction) {
  34771. return;
  34772. }
  34773. _this._delayLoadingFunction(JSON.parse(data), _this);
  34774. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34775. _this._delayInfo = [];
  34776. scene._removePendingData(_this);
  34777. var meshes = _this._meshes;
  34778. var numOfMeshes = meshes.length;
  34779. for (var index = 0; index < numOfMeshes; index++) {
  34780. _this._applyToMesh(meshes[index]);
  34781. }
  34782. if (onLoaded) {
  34783. onLoaded();
  34784. }
  34785. }, undefined, true);
  34786. };
  34787. /**
  34788. * Invert the geometry to move from a right handed system to a left handed one.
  34789. */
  34790. Geometry.prototype.toLeftHanded = function () {
  34791. // Flip faces
  34792. var tIndices = this.getIndices(false);
  34793. if (tIndices != null && tIndices.length > 0) {
  34794. for (var i = 0; i < tIndices.length; i += 3) {
  34795. var tTemp = tIndices[i + 0];
  34796. tIndices[i + 0] = tIndices[i + 2];
  34797. tIndices[i + 2] = tTemp;
  34798. }
  34799. this.setIndices(tIndices);
  34800. }
  34801. // Negate position.z
  34802. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34803. if (tPositions != null && tPositions.length > 0) {
  34804. for (var i = 0; i < tPositions.length; i += 3) {
  34805. tPositions[i + 2] = -tPositions[i + 2];
  34806. }
  34807. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34808. }
  34809. // Negate normal.z
  34810. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34811. if (tNormals != null && tNormals.length > 0) {
  34812. for (var i = 0; i < tNormals.length; i += 3) {
  34813. tNormals[i + 2] = -tNormals[i + 2];
  34814. }
  34815. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34816. }
  34817. };
  34818. // Cache
  34819. /** @ignore */
  34820. Geometry.prototype._resetPointsArrayCache = function () {
  34821. this._positions = null;
  34822. };
  34823. /** @ignore */
  34824. Geometry.prototype._generatePointsArray = function () {
  34825. if (this._positions)
  34826. return true;
  34827. this._positions = [];
  34828. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34829. if (!data) {
  34830. return false;
  34831. }
  34832. for (var index = 0; index < data.length; index += 3) {
  34833. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  34834. }
  34835. return true;
  34836. };
  34837. /**
  34838. * Gets a value indicating if the geometry is disposed
  34839. * @returns true if the geometry was disposed
  34840. */
  34841. Geometry.prototype.isDisposed = function () {
  34842. return this._isDisposed;
  34843. };
  34844. Geometry.prototype._disposeVertexArrayObjects = function () {
  34845. if (this._vertexArrayObjects) {
  34846. for (var kind in this._vertexArrayObjects) {
  34847. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  34848. }
  34849. this._vertexArrayObjects = {};
  34850. }
  34851. };
  34852. /**
  34853. * Free all associated resources
  34854. */
  34855. Geometry.prototype.dispose = function () {
  34856. var meshes = this._meshes;
  34857. var numOfMeshes = meshes.length;
  34858. var index;
  34859. for (index = 0; index < numOfMeshes; index++) {
  34860. this.releaseForMesh(meshes[index]);
  34861. }
  34862. this._meshes = [];
  34863. this._disposeVertexArrayObjects();
  34864. for (var kind in this._vertexBuffers) {
  34865. this._vertexBuffers[kind].dispose();
  34866. }
  34867. this._vertexBuffers = {};
  34868. this._totalVertices = 0;
  34869. if (this._indexBuffer) {
  34870. this._engine._releaseBuffer(this._indexBuffer);
  34871. }
  34872. this._indexBuffer = null;
  34873. this._indices = [];
  34874. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34875. this.delayLoadingFile = null;
  34876. this._delayLoadingFunction = null;
  34877. this._delayInfo = [];
  34878. this._boundingInfo = null;
  34879. this._scene.removeGeometry(this);
  34880. this._isDisposed = true;
  34881. };
  34882. /**
  34883. * Clone the current geometry into a new geometry
  34884. * @param id defines the unique ID of the new geometry
  34885. * @returns a new geometry object
  34886. */
  34887. Geometry.prototype.copy = function (id) {
  34888. var vertexData = new BABYLON.VertexData();
  34889. vertexData.indices = [];
  34890. var indices = this.getIndices();
  34891. if (indices) {
  34892. for (var index = 0; index < indices.length; index++) {
  34893. vertexData.indices.push(indices[index]);
  34894. }
  34895. }
  34896. var updatable = false;
  34897. var stopChecking = false;
  34898. var kind;
  34899. for (kind in this._vertexBuffers) {
  34900. // using slice() to make a copy of the array and not just reference it
  34901. var data = this.getVerticesData(kind);
  34902. if (data instanceof Float32Array) {
  34903. vertexData.set(new Float32Array(data), kind);
  34904. }
  34905. else {
  34906. vertexData.set(data.slice(0), kind);
  34907. }
  34908. if (!stopChecking) {
  34909. var vb = this.getVertexBuffer(kind);
  34910. if (vb) {
  34911. updatable = vb.isUpdatable();
  34912. stopChecking = !updatable;
  34913. }
  34914. }
  34915. }
  34916. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  34917. geometry.delayLoadState = this.delayLoadState;
  34918. geometry.delayLoadingFile = this.delayLoadingFile;
  34919. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34920. for (kind in this._delayInfo) {
  34921. geometry._delayInfo = geometry._delayInfo || [];
  34922. geometry._delayInfo.push(kind);
  34923. }
  34924. // Bounding info
  34925. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34926. return geometry;
  34927. };
  34928. /**
  34929. * Serialize the current geometry info (and not the vertices data) into a JSON object
  34930. * @return a JSON representation of the current geometry data (without the vertices data)
  34931. */
  34932. Geometry.prototype.serialize = function () {
  34933. var serializationObject = {};
  34934. serializationObject.id = this.id;
  34935. serializationObject.updatable = this._updatable;
  34936. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34937. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34938. }
  34939. return serializationObject;
  34940. };
  34941. Geometry.prototype.toNumberArray = function (origin) {
  34942. if (Array.isArray(origin)) {
  34943. return origin;
  34944. }
  34945. else {
  34946. return Array.prototype.slice.call(origin);
  34947. }
  34948. };
  34949. /**
  34950. * Serialize all vertices data into a JSON oject
  34951. * @returns a JSON representation of the current geometry data
  34952. */
  34953. Geometry.prototype.serializeVerticeData = function () {
  34954. var serializationObject = this.serialize();
  34955. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34956. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  34957. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34958. serializationObject.positions._updatable = true;
  34959. }
  34960. }
  34961. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34962. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  34963. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34964. serializationObject.normals._updatable = true;
  34965. }
  34966. }
  34967. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34968. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  34969. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  34970. serializationObject.tangets._updatable = true;
  34971. }
  34972. }
  34973. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34974. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  34975. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  34976. serializationObject.uvs._updatable = true;
  34977. }
  34978. }
  34979. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34980. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  34981. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  34982. serializationObject.uv2s._updatable = true;
  34983. }
  34984. }
  34985. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34986. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  34987. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  34988. serializationObject.uv3s._updatable = true;
  34989. }
  34990. }
  34991. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34992. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  34993. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  34994. serializationObject.uv4s._updatable = true;
  34995. }
  34996. }
  34997. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34998. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  34999. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35000. serializationObject.uv5s._updatable = true;
  35001. }
  35002. }
  35003. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35004. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35005. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35006. serializationObject.uv6s._updatable = true;
  35007. }
  35008. }
  35009. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35010. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35011. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35012. serializationObject.colors._updatable = true;
  35013. }
  35014. }
  35015. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35016. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35017. serializationObject.matricesIndices._isExpanded = true;
  35018. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35019. serializationObject.matricesIndices._updatable = true;
  35020. }
  35021. }
  35022. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35023. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35024. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35025. serializationObject.matricesWeights._updatable = true;
  35026. }
  35027. }
  35028. serializationObject.indices = this.toNumberArray(this.getIndices());
  35029. return serializationObject;
  35030. };
  35031. // Statics
  35032. /**
  35033. * Extracts a clone of a mesh geometry
  35034. * @param mesh defines the source mesh
  35035. * @param id defines the unique ID of the new geometry object
  35036. * @returns the new geometry object
  35037. */
  35038. Geometry.ExtractFromMesh = function (mesh, id) {
  35039. var geometry = mesh._geometry;
  35040. if (!geometry) {
  35041. return null;
  35042. }
  35043. return geometry.copy(id);
  35044. };
  35045. /**
  35046. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35047. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35048. * Be aware Math.random() could cause collisions, but:
  35049. * "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"
  35050. * @returns a string containing a new GUID
  35051. */
  35052. Geometry.RandomId = function () {
  35053. return BABYLON.Tools.RandomId();
  35054. };
  35055. /** @ignore */
  35056. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35057. var scene = mesh.getScene();
  35058. // Geometry
  35059. var geometryId = parsedGeometry.geometryId;
  35060. if (geometryId) {
  35061. var geometry = scene.getGeometryByID(geometryId);
  35062. if (geometry) {
  35063. geometry.applyToMesh(mesh);
  35064. }
  35065. }
  35066. else if (parsedGeometry instanceof ArrayBuffer) {
  35067. var binaryInfo = mesh._binaryInfo;
  35068. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35069. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35070. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35071. }
  35072. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35073. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35074. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35075. }
  35076. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35077. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35078. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35079. }
  35080. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35081. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35082. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35083. }
  35084. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35085. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35086. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35087. }
  35088. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35089. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35090. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35091. }
  35092. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35093. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35094. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35095. }
  35096. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35097. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35098. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35099. }
  35100. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35101. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35102. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35103. }
  35104. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35105. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35106. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35107. }
  35108. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35109. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35110. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35111. }
  35112. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35113. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35114. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35115. }
  35116. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35117. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35118. mesh.setIndices(indicesData, null);
  35119. }
  35120. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35121. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35122. mesh.subMeshes = [];
  35123. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35124. var materialIndex = subMeshesData[(i * 5) + 0];
  35125. var verticesStart = subMeshesData[(i * 5) + 1];
  35126. var verticesCount = subMeshesData[(i * 5) + 2];
  35127. var indexStart = subMeshesData[(i * 5) + 3];
  35128. var indexCount = subMeshesData[(i * 5) + 4];
  35129. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35130. }
  35131. }
  35132. }
  35133. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35134. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35135. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35136. if (parsedGeometry.tangents) {
  35137. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35138. }
  35139. if (parsedGeometry.uvs) {
  35140. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35141. }
  35142. if (parsedGeometry.uvs2) {
  35143. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35144. }
  35145. if (parsedGeometry.uvs3) {
  35146. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35147. }
  35148. if (parsedGeometry.uvs4) {
  35149. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35150. }
  35151. if (parsedGeometry.uvs5) {
  35152. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35153. }
  35154. if (parsedGeometry.uvs6) {
  35155. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35156. }
  35157. if (parsedGeometry.colors) {
  35158. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35159. }
  35160. if (parsedGeometry.matricesIndices) {
  35161. if (!parsedGeometry.matricesIndices._isExpanded) {
  35162. var floatIndices = [];
  35163. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35164. var matricesIndex = parsedGeometry.matricesIndices[i];
  35165. floatIndices.push(matricesIndex & 0x000000FF);
  35166. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35167. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35168. floatIndices.push(matricesIndex >> 24);
  35169. }
  35170. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35171. }
  35172. else {
  35173. delete parsedGeometry.matricesIndices._isExpanded;
  35174. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35175. }
  35176. }
  35177. if (parsedGeometry.matricesIndicesExtra) {
  35178. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35179. var floatIndices = [];
  35180. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35181. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35182. floatIndices.push(matricesIndex & 0x000000FF);
  35183. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35184. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35185. floatIndices.push(matricesIndex >> 24);
  35186. }
  35187. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35188. }
  35189. else {
  35190. delete parsedGeometry.matricesIndices._isExpanded;
  35191. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35192. }
  35193. }
  35194. if (parsedGeometry.matricesWeights) {
  35195. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35196. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35197. }
  35198. if (parsedGeometry.matricesWeightsExtra) {
  35199. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35200. }
  35201. mesh.setIndices(parsedGeometry.indices, null);
  35202. }
  35203. // SubMeshes
  35204. if (parsedGeometry.subMeshes) {
  35205. mesh.subMeshes = [];
  35206. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35207. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35208. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35209. }
  35210. }
  35211. // Flat shading
  35212. if (mesh._shouldGenerateFlatShading) {
  35213. mesh.convertToFlatShadedMesh();
  35214. delete mesh._shouldGenerateFlatShading;
  35215. }
  35216. // Update
  35217. mesh.computeWorldMatrix(true);
  35218. // Octree
  35219. var sceneOctree = scene.selectionOctree;
  35220. if (sceneOctree !== undefined && sceneOctree !== null) {
  35221. sceneOctree.addMesh(mesh);
  35222. }
  35223. };
  35224. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35225. var epsilon = 1e-3;
  35226. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35227. return;
  35228. }
  35229. var noInfluenceBoneIndex = 0.0;
  35230. if (parsedGeometry.skeletonId > -1) {
  35231. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35232. if (!skeleton) {
  35233. return;
  35234. }
  35235. noInfluenceBoneIndex = skeleton.bones.length;
  35236. }
  35237. else {
  35238. return;
  35239. }
  35240. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35241. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35242. var matricesWeights = parsedGeometry.matricesWeights;
  35243. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35244. var influencers = parsedGeometry.numBoneInfluencer;
  35245. var size = matricesWeights.length;
  35246. for (var i = 0; i < size; i += 4) {
  35247. var weight = 0.0;
  35248. var firstZeroWeight = -1;
  35249. for (var j = 0; j < 4; j++) {
  35250. var w = matricesWeights[i + j];
  35251. weight += w;
  35252. if (w < epsilon && firstZeroWeight < 0) {
  35253. firstZeroWeight = j;
  35254. }
  35255. }
  35256. if (matricesWeightsExtra) {
  35257. for (var j = 0; j < 4; j++) {
  35258. var w = matricesWeightsExtra[i + j];
  35259. weight += w;
  35260. if (w < epsilon && firstZeroWeight < 0) {
  35261. firstZeroWeight = j + 4;
  35262. }
  35263. }
  35264. }
  35265. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35266. firstZeroWeight = influencers - 1;
  35267. }
  35268. if (weight > epsilon) {
  35269. var mweight = 1.0 / weight;
  35270. for (var j = 0; j < 4; j++) {
  35271. matricesWeights[i + j] *= mweight;
  35272. }
  35273. if (matricesWeightsExtra) {
  35274. for (var j = 0; j < 4; j++) {
  35275. matricesWeightsExtra[i + j] *= mweight;
  35276. }
  35277. }
  35278. }
  35279. else {
  35280. if (firstZeroWeight >= 4) {
  35281. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35282. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35283. }
  35284. else {
  35285. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35286. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35287. }
  35288. }
  35289. }
  35290. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35291. if (parsedGeometry.matricesWeightsExtra) {
  35292. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35293. }
  35294. };
  35295. /**
  35296. * Create a new geometry from persisted data (Using .babylon file format)
  35297. * @param parsedVertexData defines the persisted data
  35298. * @param scene defines the hosting scene
  35299. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35300. * @returns the new geometry object
  35301. */
  35302. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35303. if (scene.getGeometryByID(parsedVertexData.id)) {
  35304. return null; // null since geometry could be something else than a box...
  35305. }
  35306. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35307. if (BABYLON.Tags) {
  35308. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35309. }
  35310. if (parsedVertexData.delayLoadingFile) {
  35311. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35312. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35313. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35314. geometry._delayInfo = [];
  35315. if (parsedVertexData.hasUVs) {
  35316. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35317. }
  35318. if (parsedVertexData.hasUVs2) {
  35319. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35320. }
  35321. if (parsedVertexData.hasUVs3) {
  35322. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35323. }
  35324. if (parsedVertexData.hasUVs4) {
  35325. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35326. }
  35327. if (parsedVertexData.hasUVs5) {
  35328. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35329. }
  35330. if (parsedVertexData.hasUVs6) {
  35331. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35332. }
  35333. if (parsedVertexData.hasColors) {
  35334. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35335. }
  35336. if (parsedVertexData.hasMatricesIndices) {
  35337. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35338. }
  35339. if (parsedVertexData.hasMatricesWeights) {
  35340. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35341. }
  35342. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35343. }
  35344. else {
  35345. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35346. }
  35347. scene.pushGeometry(geometry, true);
  35348. return geometry;
  35349. };
  35350. return Geometry;
  35351. }());
  35352. BABYLON.Geometry = Geometry;
  35353. // Primitives
  35354. /// Abstract class
  35355. /**
  35356. * Abstract class used to provide common services for all typed geometries
  35357. */
  35358. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35359. __extends(_PrimitiveGeometry, _super);
  35360. /**
  35361. * Creates a new typed geometry
  35362. * @param id defines the unique ID of the geometry
  35363. * @param scene defines the hosting scene
  35364. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35365. * @param mesh defines the hosting mesh (can be null)
  35366. */
  35367. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35368. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35369. if (mesh === void 0) { mesh = null; }
  35370. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35371. _this._canBeRegenerated = _canBeRegenerated;
  35372. _this._beingRegenerated = true;
  35373. _this.regenerate();
  35374. _this._beingRegenerated = false;
  35375. return _this;
  35376. }
  35377. /**
  35378. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35379. * @returns true if the geometry can be regenerated
  35380. */
  35381. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35382. return this._canBeRegenerated;
  35383. };
  35384. /**
  35385. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35386. */
  35387. _PrimitiveGeometry.prototype.regenerate = function () {
  35388. if (!this._canBeRegenerated) {
  35389. return;
  35390. }
  35391. this._beingRegenerated = true;
  35392. this.setAllVerticesData(this._regenerateVertexData(), false);
  35393. this._beingRegenerated = false;
  35394. };
  35395. /**
  35396. * Clone the geometry
  35397. * @param id defines the unique ID of the new geometry
  35398. * @returns the new geometry
  35399. */
  35400. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35401. return _super.prototype.copy.call(this, id);
  35402. };
  35403. // overrides
  35404. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35405. if (!this._beingRegenerated) {
  35406. return;
  35407. }
  35408. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35409. };
  35410. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35411. if (!this._beingRegenerated) {
  35412. return;
  35413. }
  35414. _super.prototype.setVerticesData.call(this, kind, data, false);
  35415. };
  35416. // to override
  35417. /** @ignore */
  35418. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35419. throw new Error("Abstract method");
  35420. };
  35421. _PrimitiveGeometry.prototype.copy = function (id) {
  35422. throw new Error("Must be overriden in sub-classes.");
  35423. };
  35424. _PrimitiveGeometry.prototype.serialize = function () {
  35425. var serializationObject = _super.prototype.serialize.call(this);
  35426. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35427. return serializationObject;
  35428. };
  35429. return _PrimitiveGeometry;
  35430. }(Geometry));
  35431. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35432. /**
  35433. * Creates a ribbon geometry
  35434. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35435. */
  35436. var RibbonGeometry = /** @class */ (function (_super) {
  35437. __extends(RibbonGeometry, _super);
  35438. /**
  35439. * Creates a ribbon geometry
  35440. * @param id defines the unique ID of the geometry
  35441. * @param scene defines the hosting scene
  35442. * @param pathArray defines the array of paths to use
  35443. * @param closeArray defines if the last path and the first path must be joined
  35444. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35445. * @param offset defines the offset between points
  35446. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35447. * @param mesh defines the hosting mesh (can be null)
  35448. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35449. */
  35450. function RibbonGeometry(id, scene,
  35451. /**
  35452. * Defines the array of paths to use
  35453. */
  35454. pathArray,
  35455. /**
  35456. * Defines if the last and first points of each path in your pathArray must be joined
  35457. */
  35458. closeArray,
  35459. /**
  35460. * Defines if the last and first points of each path in your pathArray must be joined
  35461. */
  35462. closePath,
  35463. /**
  35464. * Defines the offset between points
  35465. */
  35466. offset, canBeRegenerated, mesh,
  35467. /**
  35468. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35469. */
  35470. side) {
  35471. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35472. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35473. _this.pathArray = pathArray;
  35474. _this.closeArray = closeArray;
  35475. _this.closePath = closePath;
  35476. _this.offset = offset;
  35477. _this.side = side;
  35478. return _this;
  35479. }
  35480. /** @ignore */
  35481. RibbonGeometry.prototype._regenerateVertexData = function () {
  35482. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35483. };
  35484. RibbonGeometry.prototype.copy = function (id) {
  35485. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35486. };
  35487. return RibbonGeometry;
  35488. }(_PrimitiveGeometry));
  35489. BABYLON.RibbonGeometry = RibbonGeometry;
  35490. /**
  35491. * Creates a box geometry
  35492. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35493. */
  35494. var BoxGeometry = /** @class */ (function (_super) {
  35495. __extends(BoxGeometry, _super);
  35496. /**
  35497. * Creates a box geometry
  35498. * @param id defines the unique ID of the geometry
  35499. * @param scene defines the hosting scene
  35500. * @param size defines the zise of the box (width, height and depth are the same)
  35501. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35502. * @param mesh defines the hosting mesh (can be null)
  35503. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35504. */
  35505. function BoxGeometry(id, scene,
  35506. /**
  35507. * Defines the zise of the box (width, height and depth are the same)
  35508. */
  35509. size, canBeRegenerated, mesh,
  35510. /**
  35511. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35512. */
  35513. side) {
  35514. if (mesh === void 0) { mesh = null; }
  35515. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35516. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35517. _this.size = size;
  35518. _this.side = side;
  35519. return _this;
  35520. }
  35521. BoxGeometry.prototype._regenerateVertexData = function () {
  35522. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35523. };
  35524. BoxGeometry.prototype.copy = function (id) {
  35525. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35526. };
  35527. BoxGeometry.prototype.serialize = function () {
  35528. var serializationObject = _super.prototype.serialize.call(this);
  35529. serializationObject.size = this.size;
  35530. return serializationObject;
  35531. };
  35532. BoxGeometry.Parse = function (parsedBox, scene) {
  35533. if (scene.getGeometryByID(parsedBox.id)) {
  35534. return null; // null since geometry could be something else than a box...
  35535. }
  35536. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35537. if (BABYLON.Tags) {
  35538. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35539. }
  35540. scene.pushGeometry(box, true);
  35541. return box;
  35542. };
  35543. return BoxGeometry;
  35544. }(_PrimitiveGeometry));
  35545. BABYLON.BoxGeometry = BoxGeometry;
  35546. /**
  35547. * Creates a sphere geometry
  35548. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35549. */
  35550. var SphereGeometry = /** @class */ (function (_super) {
  35551. __extends(SphereGeometry, _super);
  35552. /**
  35553. * Create a new sphere geometry
  35554. * @param id defines the unique ID of the geometry
  35555. * @param scene defines the hosting scene
  35556. * @param segments defines the number of segments to use to create the sphere
  35557. * @param diameter defines the diameter of the sphere
  35558. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35559. * @param mesh defines the hosting mesh (can be null)
  35560. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35561. */
  35562. function SphereGeometry(id, scene,
  35563. /**
  35564. * Defines the number of segments to use to create the sphere
  35565. */
  35566. segments,
  35567. /**
  35568. * Defines the diameter of the sphere
  35569. */
  35570. diameter, canBeRegenerated, mesh,
  35571. /**
  35572. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35573. */
  35574. side) {
  35575. if (mesh === void 0) { mesh = null; }
  35576. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35577. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35578. _this.segments = segments;
  35579. _this.diameter = diameter;
  35580. _this.side = side;
  35581. return _this;
  35582. }
  35583. SphereGeometry.prototype._regenerateVertexData = function () {
  35584. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35585. };
  35586. SphereGeometry.prototype.copy = function (id) {
  35587. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35588. };
  35589. SphereGeometry.prototype.serialize = function () {
  35590. var serializationObject = _super.prototype.serialize.call(this);
  35591. serializationObject.segments = this.segments;
  35592. serializationObject.diameter = this.diameter;
  35593. return serializationObject;
  35594. };
  35595. SphereGeometry.Parse = function (parsedSphere, scene) {
  35596. if (scene.getGeometryByID(parsedSphere.id)) {
  35597. return null; // null since geometry could be something else than a sphere...
  35598. }
  35599. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35600. if (BABYLON.Tags) {
  35601. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35602. }
  35603. scene.pushGeometry(sphere, true);
  35604. return sphere;
  35605. };
  35606. return SphereGeometry;
  35607. }(_PrimitiveGeometry));
  35608. BABYLON.SphereGeometry = SphereGeometry;
  35609. /**
  35610. * Creates a disc geometry
  35611. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35612. */
  35613. var DiscGeometry = /** @class */ (function (_super) {
  35614. __extends(DiscGeometry, _super);
  35615. /**
  35616. * Creates a new disc geometry
  35617. * @param id defines the unique ID of the geometry
  35618. * @param scene defines the hosting scene
  35619. * @param radius defines the radius of the disc
  35620. * @param tessellation defines the tesselation factor to apply to the disc
  35621. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35622. * @param mesh defines the hosting mesh (can be null)
  35623. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35624. */
  35625. function DiscGeometry(id, scene,
  35626. /**
  35627. * Defines the radius of the disc
  35628. */
  35629. radius,
  35630. /**
  35631. * Defines the tesselation factor to apply to the disc
  35632. */
  35633. tessellation, canBeRegenerated, mesh,
  35634. /**
  35635. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35636. */
  35637. side) {
  35638. if (mesh === void 0) { mesh = null; }
  35639. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35640. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35641. _this.radius = radius;
  35642. _this.tessellation = tessellation;
  35643. _this.side = side;
  35644. return _this;
  35645. }
  35646. DiscGeometry.prototype._regenerateVertexData = function () {
  35647. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35648. };
  35649. DiscGeometry.prototype.copy = function (id) {
  35650. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35651. };
  35652. return DiscGeometry;
  35653. }(_PrimitiveGeometry));
  35654. BABYLON.DiscGeometry = DiscGeometry;
  35655. /**
  35656. * Creates a new cylinder geometry
  35657. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35658. */
  35659. var CylinderGeometry = /** @class */ (function (_super) {
  35660. __extends(CylinderGeometry, _super);
  35661. /**
  35662. * Creates a new cylinder geometry
  35663. * @param id defines the unique ID of the geometry
  35664. * @param scene defines the hosting scene
  35665. * @param height defines the height of the cylinder
  35666. * @param diameterTop defines the diameter of the cylinder's top cap
  35667. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35668. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35669. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35670. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35671. * @param mesh defines the hosting mesh (can be null)
  35672. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35673. */
  35674. function CylinderGeometry(id, scene,
  35675. /**
  35676. * Defines the height of the cylinder
  35677. */
  35678. height,
  35679. /**
  35680. * Defines the diameter of the cylinder's top cap
  35681. */
  35682. diameterTop,
  35683. /**
  35684. * Defines the diameter of the cylinder's bottom cap
  35685. */
  35686. diameterBottom,
  35687. /**
  35688. * Defines the tessellation factor to apply to the cylinder
  35689. */
  35690. tessellation,
  35691. /**
  35692. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  35693. */
  35694. subdivisions, canBeRegenerated, mesh,
  35695. /**
  35696. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35697. */
  35698. side) {
  35699. if (subdivisions === void 0) { subdivisions = 1; }
  35700. if (mesh === void 0) { mesh = null; }
  35701. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35702. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35703. _this.height = height;
  35704. _this.diameterTop = diameterTop;
  35705. _this.diameterBottom = diameterBottom;
  35706. _this.tessellation = tessellation;
  35707. _this.subdivisions = subdivisions;
  35708. _this.side = side;
  35709. return _this;
  35710. }
  35711. CylinderGeometry.prototype._regenerateVertexData = function () {
  35712. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35713. };
  35714. CylinderGeometry.prototype.copy = function (id) {
  35715. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35716. };
  35717. CylinderGeometry.prototype.serialize = function () {
  35718. var serializationObject = _super.prototype.serialize.call(this);
  35719. serializationObject.height = this.height;
  35720. serializationObject.diameterTop = this.diameterTop;
  35721. serializationObject.diameterBottom = this.diameterBottom;
  35722. serializationObject.tessellation = this.tessellation;
  35723. return serializationObject;
  35724. };
  35725. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  35726. if (scene.getGeometryByID(parsedCylinder.id)) {
  35727. return null; // null since geometry could be something else than a cylinder...
  35728. }
  35729. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35730. if (BABYLON.Tags) {
  35731. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35732. }
  35733. scene.pushGeometry(cylinder, true);
  35734. return cylinder;
  35735. };
  35736. return CylinderGeometry;
  35737. }(_PrimitiveGeometry));
  35738. BABYLON.CylinderGeometry = CylinderGeometry;
  35739. /**
  35740. * Creates a new torus geometry
  35741. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  35742. */
  35743. var TorusGeometry = /** @class */ (function (_super) {
  35744. __extends(TorusGeometry, _super);
  35745. /**
  35746. * Creates a new torus geometry
  35747. * @param id defines the unique ID of the geometry
  35748. * @param scene defines the hosting scene
  35749. * @param diameter defines the diameter of the torus
  35750. * @param thickness defines the thickness of the torus (ie. internal diameter)
  35751. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  35752. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35753. * @param mesh defines the hosting mesh (can be null)
  35754. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35755. */
  35756. function TorusGeometry(id, scene,
  35757. /**
  35758. * Defines the diameter of the torus
  35759. */
  35760. diameter,
  35761. /**
  35762. * Defines the thickness of the torus (ie. internal diameter)
  35763. */
  35764. thickness,
  35765. /**
  35766. * Defines the tesselation factor to apply to the torus
  35767. */
  35768. tessellation, canBeRegenerated, mesh,
  35769. /**
  35770. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35771. */
  35772. side) {
  35773. if (mesh === void 0) { mesh = null; }
  35774. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35775. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35776. _this.diameter = diameter;
  35777. _this.thickness = thickness;
  35778. _this.tessellation = tessellation;
  35779. _this.side = side;
  35780. return _this;
  35781. }
  35782. TorusGeometry.prototype._regenerateVertexData = function () {
  35783. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35784. };
  35785. TorusGeometry.prototype.copy = function (id) {
  35786. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35787. };
  35788. TorusGeometry.prototype.serialize = function () {
  35789. var serializationObject = _super.prototype.serialize.call(this);
  35790. serializationObject.diameter = this.diameter;
  35791. serializationObject.thickness = this.thickness;
  35792. serializationObject.tessellation = this.tessellation;
  35793. return serializationObject;
  35794. };
  35795. TorusGeometry.Parse = function (parsedTorus, scene) {
  35796. if (scene.getGeometryByID(parsedTorus.id)) {
  35797. return null; // null since geometry could be something else than a torus...
  35798. }
  35799. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35800. if (BABYLON.Tags) {
  35801. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35802. }
  35803. scene.pushGeometry(torus, true);
  35804. return torus;
  35805. };
  35806. return TorusGeometry;
  35807. }(_PrimitiveGeometry));
  35808. BABYLON.TorusGeometry = TorusGeometry;
  35809. /**
  35810. * Creates a new ground geometry
  35811. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  35812. */
  35813. var GroundGeometry = /** @class */ (function (_super) {
  35814. __extends(GroundGeometry, _super);
  35815. /**
  35816. * Creates a new ground geometry
  35817. * @param id defines the unique ID of the geometry
  35818. * @param scene defines the hosting scene
  35819. * @param width defines the width of the ground
  35820. * @param height defines the height of the ground
  35821. * @param subdivisions defines the subdivisions to apply to the ground
  35822. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35823. * @param mesh defines the hosting mesh (can be null)
  35824. */
  35825. function GroundGeometry(id, scene,
  35826. /**
  35827. * Defines the width of the ground
  35828. */
  35829. width,
  35830. /**
  35831. * Defines the height of the ground
  35832. */
  35833. height,
  35834. /**
  35835. * Defines the subdivisions to apply to the ground
  35836. */
  35837. subdivisions, canBeRegenerated, mesh) {
  35838. if (mesh === void 0) { mesh = null; }
  35839. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35840. _this.width = width;
  35841. _this.height = height;
  35842. _this.subdivisions = subdivisions;
  35843. return _this;
  35844. }
  35845. GroundGeometry.prototype._regenerateVertexData = function () {
  35846. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35847. };
  35848. GroundGeometry.prototype.copy = function (id) {
  35849. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35850. };
  35851. GroundGeometry.prototype.serialize = function () {
  35852. var serializationObject = _super.prototype.serialize.call(this);
  35853. serializationObject.width = this.width;
  35854. serializationObject.height = this.height;
  35855. serializationObject.subdivisions = this.subdivisions;
  35856. return serializationObject;
  35857. };
  35858. GroundGeometry.Parse = function (parsedGround, scene) {
  35859. if (scene.getGeometryByID(parsedGround.id)) {
  35860. return null; // null since geometry could be something else than a ground...
  35861. }
  35862. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35863. if (BABYLON.Tags) {
  35864. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35865. }
  35866. scene.pushGeometry(ground, true);
  35867. return ground;
  35868. };
  35869. return GroundGeometry;
  35870. }(_PrimitiveGeometry));
  35871. BABYLON.GroundGeometry = GroundGeometry;
  35872. /**
  35873. * Creates a tiled ground geometry
  35874. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  35875. */
  35876. var TiledGroundGeometry = /** @class */ (function (_super) {
  35877. __extends(TiledGroundGeometry, _super);
  35878. /**
  35879. * Creates a tiled ground geometry
  35880. * @param id defines the unique ID of the geometry
  35881. * @param scene defines the hosting scene
  35882. * @param xmin defines the minimum value on X axis
  35883. * @param zmin defines the minimum value on Z axis
  35884. * @param xmax defines the maximum value on X axis
  35885. * @param zmax defines the maximum value on Z axis
  35886. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  35887. * @param precision defines the precision to use when computing the tiles
  35888. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35889. * @param mesh defines the hosting mesh (can be null)
  35890. */
  35891. function TiledGroundGeometry(id, scene,
  35892. /**
  35893. * Defines the minimum value on X axis
  35894. */
  35895. xmin,
  35896. /**
  35897. * Defines the minimum value on Z axis
  35898. */
  35899. zmin,
  35900. /**
  35901. * Defines the maximum value on X axis
  35902. */
  35903. xmax,
  35904. /**
  35905. * Defines the maximum value on Z axis
  35906. */
  35907. zmax,
  35908. /**
  35909. * Defines the subdivisions to apply to the ground
  35910. */
  35911. subdivisions,
  35912. /**
  35913. * Defines the precision to use when computing the tiles
  35914. */
  35915. precision, canBeRegenerated, mesh) {
  35916. if (mesh === void 0) { mesh = null; }
  35917. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35918. _this.xmin = xmin;
  35919. _this.zmin = zmin;
  35920. _this.xmax = xmax;
  35921. _this.zmax = zmax;
  35922. _this.subdivisions = subdivisions;
  35923. _this.precision = precision;
  35924. return _this;
  35925. }
  35926. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  35927. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35928. };
  35929. TiledGroundGeometry.prototype.copy = function (id) {
  35930. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35931. };
  35932. return TiledGroundGeometry;
  35933. }(_PrimitiveGeometry));
  35934. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  35935. /**
  35936. * Creates a plane geometry
  35937. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  35938. */
  35939. var PlaneGeometry = /** @class */ (function (_super) {
  35940. __extends(PlaneGeometry, _super);
  35941. /**
  35942. * Creates a plane geometry
  35943. * @param id defines the unique ID of the geometry
  35944. * @param scene defines the hosting scene
  35945. * @param size defines the size of the plane (width === height)
  35946. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35947. * @param mesh defines the hosting mesh (can be null)
  35948. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35949. */
  35950. function PlaneGeometry(id, scene,
  35951. /**
  35952. * Defines the size of the plane (width === height)
  35953. */
  35954. size, canBeRegenerated, mesh,
  35955. /**
  35956. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35957. */
  35958. side) {
  35959. if (mesh === void 0) { mesh = null; }
  35960. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35961. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35962. _this.size = size;
  35963. _this.side = side;
  35964. return _this;
  35965. }
  35966. PlaneGeometry.prototype._regenerateVertexData = function () {
  35967. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35968. };
  35969. PlaneGeometry.prototype.copy = function (id) {
  35970. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35971. };
  35972. PlaneGeometry.prototype.serialize = function () {
  35973. var serializationObject = _super.prototype.serialize.call(this);
  35974. serializationObject.size = this.size;
  35975. return serializationObject;
  35976. };
  35977. PlaneGeometry.Parse = function (parsedPlane, scene) {
  35978. if (scene.getGeometryByID(parsedPlane.id)) {
  35979. return null; // null since geometry could be something else than a ground...
  35980. }
  35981. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35982. if (BABYLON.Tags) {
  35983. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35984. }
  35985. scene.pushGeometry(plane, true);
  35986. return plane;
  35987. };
  35988. return PlaneGeometry;
  35989. }(_PrimitiveGeometry));
  35990. BABYLON.PlaneGeometry = PlaneGeometry;
  35991. /**
  35992. * Creates a torus knot geometry
  35993. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  35994. */
  35995. var TorusKnotGeometry = /** @class */ (function (_super) {
  35996. __extends(TorusKnotGeometry, _super);
  35997. /**
  35998. * Creates a torus knot geometry
  35999. * @param id defines the unique ID of the geometry
  36000. * @param scene defines the hosting scene
  36001. * @param radius defines the radius of the torus knot
  36002. * @param tube defines the thickness of the torus knot tube
  36003. * @param radialSegments defines the number of radial segments
  36004. * @param tubularSegments defines the number of tubular segments
  36005. * @param p defines the first number of windings
  36006. * @param q defines the second number of windings
  36007. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36008. * @param mesh defines the hosting mesh (can be null)
  36009. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36010. */
  36011. function TorusKnotGeometry(id, scene,
  36012. /**
  36013. * Defines the radius of the torus knot
  36014. */
  36015. radius,
  36016. /**
  36017. * Defines the thickness of the torus knot tube
  36018. */
  36019. tube,
  36020. /**
  36021. * Defines the number of radial segments
  36022. */
  36023. radialSegments,
  36024. /**
  36025. * Defines the number of tubular segments
  36026. */
  36027. tubularSegments,
  36028. /**
  36029. * Defines the first number of windings
  36030. */
  36031. p,
  36032. /**
  36033. * Defines the second number of windings
  36034. */
  36035. q, canBeRegenerated, mesh,
  36036. /**
  36037. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36038. */
  36039. side) {
  36040. if (mesh === void 0) { mesh = null; }
  36041. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36042. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36043. _this.radius = radius;
  36044. _this.tube = tube;
  36045. _this.radialSegments = radialSegments;
  36046. _this.tubularSegments = tubularSegments;
  36047. _this.p = p;
  36048. _this.q = q;
  36049. _this.side = side;
  36050. return _this;
  36051. }
  36052. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36053. 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 });
  36054. };
  36055. TorusKnotGeometry.prototype.copy = function (id) {
  36056. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36057. };
  36058. TorusKnotGeometry.prototype.serialize = function () {
  36059. var serializationObject = _super.prototype.serialize.call(this);
  36060. serializationObject.radius = this.radius;
  36061. serializationObject.tube = this.tube;
  36062. serializationObject.radialSegments = this.radialSegments;
  36063. serializationObject.tubularSegments = this.tubularSegments;
  36064. serializationObject.p = this.p;
  36065. serializationObject.q = this.q;
  36066. return serializationObject;
  36067. };
  36068. ;
  36069. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36070. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36071. return null; // null since geometry could be something else than a ground...
  36072. }
  36073. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36074. if (BABYLON.Tags) {
  36075. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36076. }
  36077. scene.pushGeometry(torusKnot, true);
  36078. return torusKnot;
  36079. };
  36080. return TorusKnotGeometry;
  36081. }(_PrimitiveGeometry));
  36082. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36083. //}
  36084. })(BABYLON || (BABYLON = {}));
  36085. //# sourceMappingURL=babylon.geometry.js.map
  36086. var BABYLON;
  36087. (function (BABYLON) {
  36088. /**
  36089. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36090. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36091. */
  36092. var PostProcessManager = /** @class */ (function () {
  36093. /**
  36094. * Creates a new instance of @see PostProcess
  36095. * @param scene The scene that the post process is associated with.
  36096. */
  36097. function PostProcessManager(scene) {
  36098. this._vertexBuffers = {};
  36099. this._scene = scene;
  36100. }
  36101. PostProcessManager.prototype._prepareBuffers = function () {
  36102. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36103. return;
  36104. }
  36105. // VBO
  36106. var vertices = [];
  36107. vertices.push(1, 1);
  36108. vertices.push(-1, 1);
  36109. vertices.push(-1, -1);
  36110. vertices.push(1, -1);
  36111. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36112. this._buildIndexBuffer();
  36113. };
  36114. PostProcessManager.prototype._buildIndexBuffer = function () {
  36115. // Indices
  36116. var indices = [];
  36117. indices.push(0);
  36118. indices.push(1);
  36119. indices.push(2);
  36120. indices.push(0);
  36121. indices.push(2);
  36122. indices.push(3);
  36123. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36124. };
  36125. /**
  36126. * Rebuilds the vertex buffers of the manager.
  36127. */
  36128. PostProcessManager.prototype._rebuild = function () {
  36129. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36130. if (!vb) {
  36131. return;
  36132. }
  36133. vb._rebuild();
  36134. this._buildIndexBuffer();
  36135. };
  36136. // Methods
  36137. /**
  36138. * Prepares a frame to be run through a post process.
  36139. * @param sourceTexture The input texture to the post procesess. (default: null)
  36140. * @param postProcesses An array of post processes to be run. (default: null)
  36141. * @returns True if the post processes were able to be run.
  36142. */
  36143. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36144. if (sourceTexture === void 0) { sourceTexture = null; }
  36145. if (postProcesses === void 0) { postProcesses = null; }
  36146. var camera = this._scene.activeCamera;
  36147. if (!camera) {
  36148. return false;
  36149. }
  36150. var postProcesses = postProcesses || camera._postProcesses;
  36151. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36152. return false;
  36153. }
  36154. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36155. return true;
  36156. };
  36157. /**
  36158. * Manually render a set of post processes to a texture.
  36159. * @param postProcesses An array of post processes to be run.
  36160. * @param targetTexture The target texture to render to.
  36161. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36162. */
  36163. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36164. if (targetTexture === void 0) { targetTexture = null; }
  36165. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36166. var engine = this._scene.getEngine();
  36167. for (var index = 0; index < postProcesses.length; index++) {
  36168. if (index < postProcesses.length - 1) {
  36169. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36170. }
  36171. else {
  36172. if (targetTexture) {
  36173. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36174. }
  36175. else {
  36176. engine.restoreDefaultFramebuffer();
  36177. }
  36178. }
  36179. var pp = postProcesses[index];
  36180. var effect = pp.apply();
  36181. if (effect) {
  36182. pp.onBeforeRenderObservable.notifyObservers(effect);
  36183. // VBOs
  36184. this._prepareBuffers();
  36185. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36186. // Draw order
  36187. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36188. pp.onAfterRenderObservable.notifyObservers(effect);
  36189. }
  36190. }
  36191. // Restore depth buffer
  36192. engine.setDepthBuffer(true);
  36193. engine.setDepthWrite(true);
  36194. };
  36195. /**
  36196. * Finalize the result of the output of the postprocesses.
  36197. * @param doNotPresent If true the result will not be displayed to the screen.
  36198. * @param targetTexture The target texture to render to.
  36199. * @param faceIndex The index of the face to bind the target texture to.
  36200. * @param postProcesses The array of post processes to render.
  36201. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36202. */
  36203. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36204. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36205. var camera = this._scene.activeCamera;
  36206. if (!camera) {
  36207. return;
  36208. }
  36209. postProcesses = postProcesses || camera._postProcesses;
  36210. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36211. return;
  36212. }
  36213. var engine = this._scene.getEngine();
  36214. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36215. if (index < len - 1) {
  36216. postProcesses[index + 1].activate(camera, targetTexture);
  36217. }
  36218. else {
  36219. if (targetTexture) {
  36220. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36221. }
  36222. else {
  36223. engine.restoreDefaultFramebuffer();
  36224. }
  36225. }
  36226. if (doNotPresent) {
  36227. break;
  36228. }
  36229. var pp = postProcesses[index];
  36230. var effect = pp.apply();
  36231. if (effect) {
  36232. pp.onBeforeRenderObservable.notifyObservers(effect);
  36233. // VBOs
  36234. this._prepareBuffers();
  36235. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36236. // Draw order
  36237. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36238. pp.onAfterRenderObservable.notifyObservers(effect);
  36239. }
  36240. }
  36241. // Restore states
  36242. engine.setDepthBuffer(true);
  36243. engine.setDepthWrite(true);
  36244. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36245. };
  36246. /**
  36247. * Disposes of the post process manager.
  36248. */
  36249. PostProcessManager.prototype.dispose = function () {
  36250. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36251. if (buffer) {
  36252. buffer.dispose();
  36253. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36254. }
  36255. if (this._indexBuffer) {
  36256. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36257. this._indexBuffer = null;
  36258. }
  36259. };
  36260. return PostProcessManager;
  36261. }());
  36262. BABYLON.PostProcessManager = PostProcessManager;
  36263. })(BABYLON || (BABYLON = {}));
  36264. //# sourceMappingURL=babylon.postProcessManager.js.map
  36265. var BABYLON;
  36266. (function (BABYLON) {
  36267. /**
  36268. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36269. */
  36270. var PerformanceMonitor = /** @class */ (function () {
  36271. /**
  36272. * constructor
  36273. * @param frameSampleSize The number of samples required to saturate the sliding window
  36274. */
  36275. function PerformanceMonitor(frameSampleSize) {
  36276. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36277. this._enabled = true;
  36278. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36279. }
  36280. /**
  36281. * Samples current frame
  36282. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36283. */
  36284. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36285. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36286. if (!this._enabled)
  36287. return;
  36288. if (this._lastFrameTimeMs != null) {
  36289. var dt = timeMs - this._lastFrameTimeMs;
  36290. this._rollingFrameTime.add(dt);
  36291. }
  36292. this._lastFrameTimeMs = timeMs;
  36293. };
  36294. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36295. /**
  36296. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36297. * @return Average frame time in milliseconds
  36298. */
  36299. get: function () {
  36300. return this._rollingFrameTime.average;
  36301. },
  36302. enumerable: true,
  36303. configurable: true
  36304. });
  36305. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36306. /**
  36307. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36308. * @return Frame time variance in milliseconds squared
  36309. */
  36310. get: function () {
  36311. return this._rollingFrameTime.variance;
  36312. },
  36313. enumerable: true,
  36314. configurable: true
  36315. });
  36316. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36317. /**
  36318. * Returns the frame time of the most recent frame
  36319. * @return Frame time in milliseconds
  36320. */
  36321. get: function () {
  36322. return this._rollingFrameTime.history(0);
  36323. },
  36324. enumerable: true,
  36325. configurable: true
  36326. });
  36327. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36328. /**
  36329. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36330. * @return Framerate in frames per second
  36331. */
  36332. get: function () {
  36333. return 1000.0 / this._rollingFrameTime.average;
  36334. },
  36335. enumerable: true,
  36336. configurable: true
  36337. });
  36338. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36339. /**
  36340. * Returns the average framerate in frames per second using the most recent frame time
  36341. * @return Framerate in frames per second
  36342. */
  36343. get: function () {
  36344. var history = this._rollingFrameTime.history(0);
  36345. if (history === 0) {
  36346. return 0;
  36347. }
  36348. return 1000.0 / history;
  36349. },
  36350. enumerable: true,
  36351. configurable: true
  36352. });
  36353. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36354. /**
  36355. * Returns true if enough samples have been taken to completely fill the sliding window
  36356. * @return true if saturated
  36357. */
  36358. get: function () {
  36359. return this._rollingFrameTime.isSaturated();
  36360. },
  36361. enumerable: true,
  36362. configurable: true
  36363. });
  36364. /**
  36365. * Enables contributions to the sliding window sample set
  36366. */
  36367. PerformanceMonitor.prototype.enable = function () {
  36368. this._enabled = true;
  36369. };
  36370. /**
  36371. * Disables contributions to the sliding window sample set
  36372. * Samples will not be interpolated over the disabled period
  36373. */
  36374. PerformanceMonitor.prototype.disable = function () {
  36375. this._enabled = false;
  36376. //clear last sample to avoid interpolating over the disabled period when next enabled
  36377. this._lastFrameTimeMs = null;
  36378. };
  36379. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36380. /**
  36381. * Returns true if sampling is enabled
  36382. * @return true if enabled
  36383. */
  36384. get: function () {
  36385. return this._enabled;
  36386. },
  36387. enumerable: true,
  36388. configurable: true
  36389. });
  36390. /**
  36391. * Resets performance monitor
  36392. */
  36393. PerformanceMonitor.prototype.reset = function () {
  36394. //clear last sample to avoid interpolating over the disabled period when next enabled
  36395. this._lastFrameTimeMs = null;
  36396. //wipe record
  36397. this._rollingFrameTime.reset();
  36398. };
  36399. return PerformanceMonitor;
  36400. }());
  36401. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36402. /**
  36403. * RollingAverage
  36404. *
  36405. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36406. */
  36407. var RollingAverage = /** @class */ (function () {
  36408. /**
  36409. * constructor
  36410. * @param length The number of samples required to saturate the sliding window
  36411. */
  36412. function RollingAverage(length) {
  36413. this._samples = new Array(length);
  36414. this.reset();
  36415. }
  36416. /**
  36417. * Adds a sample to the sample set
  36418. * @param v The sample value
  36419. */
  36420. RollingAverage.prototype.add = function (v) {
  36421. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36422. var delta;
  36423. //we need to check if we've already wrapped round
  36424. if (this.isSaturated()) {
  36425. //remove bottom of stack from mean
  36426. var bottomValue = this._samples[this._pos];
  36427. delta = bottomValue - this.average;
  36428. this.average -= delta / (this._sampleCount - 1);
  36429. this._m2 -= delta * (bottomValue - this.average);
  36430. }
  36431. else {
  36432. this._sampleCount++;
  36433. }
  36434. //add new value to mean
  36435. delta = v - this.average;
  36436. this.average += delta / (this._sampleCount);
  36437. this._m2 += delta * (v - this.average);
  36438. //set the new variance
  36439. this.variance = this._m2 / (this._sampleCount - 1);
  36440. this._samples[this._pos] = v;
  36441. this._pos++;
  36442. this._pos %= this._samples.length; //positive wrap around
  36443. };
  36444. /**
  36445. * Returns previously added values or null if outside of history or outside the sliding window domain
  36446. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36447. * @return Value previously recorded with add() or null if outside of range
  36448. */
  36449. RollingAverage.prototype.history = function (i) {
  36450. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36451. return 0;
  36452. }
  36453. var i0 = this._wrapPosition(this._pos - 1.0);
  36454. return this._samples[this._wrapPosition(i0 - i)];
  36455. };
  36456. /**
  36457. * Returns true if enough samples have been taken to completely fill the sliding window
  36458. * @return true if sample-set saturated
  36459. */
  36460. RollingAverage.prototype.isSaturated = function () {
  36461. return this._sampleCount >= this._samples.length;
  36462. };
  36463. /**
  36464. * Resets the rolling average (equivalent to 0 samples taken so far)
  36465. */
  36466. RollingAverage.prototype.reset = function () {
  36467. this.average = 0;
  36468. this.variance = 0;
  36469. this._sampleCount = 0;
  36470. this._pos = 0;
  36471. this._m2 = 0;
  36472. };
  36473. /**
  36474. * Wraps a value around the sample range boundaries
  36475. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36476. * @return Wrapped position in sample range
  36477. */
  36478. RollingAverage.prototype._wrapPosition = function (i) {
  36479. var max = this._samples.length;
  36480. return ((i % max) + max) % max;
  36481. };
  36482. return RollingAverage;
  36483. }());
  36484. BABYLON.RollingAverage = RollingAverage;
  36485. })(BABYLON || (BABYLON = {}));
  36486. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36487. var BABYLON;
  36488. (function (BABYLON) {
  36489. /**
  36490. * This groups together the common properties used for image processing either in direct forward pass
  36491. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36492. * or not.
  36493. */
  36494. var ImageProcessingConfiguration = /** @class */ (function () {
  36495. function ImageProcessingConfiguration() {
  36496. /**
  36497. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36498. */
  36499. this.colorCurves = new BABYLON.ColorCurves();
  36500. this._colorCurvesEnabled = false;
  36501. this._colorGradingEnabled = false;
  36502. this._colorGradingWithGreenDepth = true;
  36503. this._colorGradingBGR = true;
  36504. this._exposure = 1.0;
  36505. this._toneMappingEnabled = false;
  36506. this._contrast = 1.0;
  36507. /**
  36508. * Vignette stretch size.
  36509. */
  36510. this.vignetteStretch = 0;
  36511. /**
  36512. * Vignette centre X Offset.
  36513. */
  36514. this.vignetteCentreX = 0;
  36515. /**
  36516. * Vignette centre Y Offset.
  36517. */
  36518. this.vignetteCentreY = 0;
  36519. /**
  36520. * Vignette weight or intensity of the vignette effect.
  36521. */
  36522. this.vignetteWeight = 1.5;
  36523. /**
  36524. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36525. * if vignetteEnabled is set to true.
  36526. */
  36527. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36528. /**
  36529. * Camera field of view used by the Vignette effect.
  36530. */
  36531. this.vignetteCameraFov = 0.5;
  36532. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36533. this._vignetteEnabled = false;
  36534. this._applyByPostProcess = false;
  36535. this._isEnabled = true;
  36536. /**
  36537. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36538. * @type {BABYLON.Observable}
  36539. */
  36540. this.onUpdateParameters = new BABYLON.Observable();
  36541. }
  36542. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36543. /**
  36544. * Gets wether the color curves effect is enabled.
  36545. */
  36546. get: function () {
  36547. return this._colorCurvesEnabled;
  36548. },
  36549. /**
  36550. * Sets wether the color curves effect is enabled.
  36551. */
  36552. set: function (value) {
  36553. if (this._colorCurvesEnabled === value) {
  36554. return;
  36555. }
  36556. this._colorCurvesEnabled = value;
  36557. this._updateParameters();
  36558. },
  36559. enumerable: true,
  36560. configurable: true
  36561. });
  36562. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36563. /**
  36564. * Gets wether the color grading effect is enabled.
  36565. */
  36566. get: function () {
  36567. return this._colorGradingEnabled;
  36568. },
  36569. /**
  36570. * Sets wether the color grading effect is enabled.
  36571. */
  36572. set: function (value) {
  36573. if (this._colorGradingEnabled === value) {
  36574. return;
  36575. }
  36576. this._colorGradingEnabled = value;
  36577. this._updateParameters();
  36578. },
  36579. enumerable: true,
  36580. configurable: true
  36581. });
  36582. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36583. /**
  36584. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36585. */
  36586. get: function () {
  36587. return this._colorGradingWithGreenDepth;
  36588. },
  36589. /**
  36590. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36591. */
  36592. set: function (value) {
  36593. if (this._colorGradingWithGreenDepth === value) {
  36594. return;
  36595. }
  36596. this._colorGradingWithGreenDepth = value;
  36597. this._updateParameters();
  36598. },
  36599. enumerable: true,
  36600. configurable: true
  36601. });
  36602. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36603. /**
  36604. * Gets wether the color grading texture contains BGR values.
  36605. */
  36606. get: function () {
  36607. return this._colorGradingBGR;
  36608. },
  36609. /**
  36610. * Sets wether the color grading texture contains BGR values.
  36611. */
  36612. set: function (value) {
  36613. if (this._colorGradingBGR === value) {
  36614. return;
  36615. }
  36616. this._colorGradingBGR = value;
  36617. this._updateParameters();
  36618. },
  36619. enumerable: true,
  36620. configurable: true
  36621. });
  36622. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36623. /**
  36624. * Gets the Exposure used in the effect.
  36625. */
  36626. get: function () {
  36627. return this._exposure;
  36628. },
  36629. /**
  36630. * Sets the Exposure used in the effect.
  36631. */
  36632. set: function (value) {
  36633. if (this._exposure === value) {
  36634. return;
  36635. }
  36636. this._exposure = value;
  36637. this._updateParameters();
  36638. },
  36639. enumerable: true,
  36640. configurable: true
  36641. });
  36642. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36643. /**
  36644. * Gets wether the tone mapping effect is enabled.
  36645. */
  36646. get: function () {
  36647. return this._toneMappingEnabled;
  36648. },
  36649. /**
  36650. * Sets wether the tone mapping effect is enabled.
  36651. */
  36652. set: function (value) {
  36653. if (this._toneMappingEnabled === value) {
  36654. return;
  36655. }
  36656. this._toneMappingEnabled = value;
  36657. this._updateParameters();
  36658. },
  36659. enumerable: true,
  36660. configurable: true
  36661. });
  36662. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36663. /**
  36664. * Gets the contrast used in the effect.
  36665. */
  36666. get: function () {
  36667. return this._contrast;
  36668. },
  36669. /**
  36670. * Sets the contrast used in the effect.
  36671. */
  36672. set: function (value) {
  36673. if (this._contrast === value) {
  36674. return;
  36675. }
  36676. this._contrast = value;
  36677. this._updateParameters();
  36678. },
  36679. enumerable: true,
  36680. configurable: true
  36681. });
  36682. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  36683. /**
  36684. * Gets the vignette blend mode allowing different kind of effect.
  36685. */
  36686. get: function () {
  36687. return this._vignetteBlendMode;
  36688. },
  36689. /**
  36690. * Sets the vignette blend mode allowing different kind of effect.
  36691. */
  36692. set: function (value) {
  36693. if (this._vignetteBlendMode === value) {
  36694. return;
  36695. }
  36696. this._vignetteBlendMode = value;
  36697. this._updateParameters();
  36698. },
  36699. enumerable: true,
  36700. configurable: true
  36701. });
  36702. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  36703. /**
  36704. * Gets wether the vignette effect is enabled.
  36705. */
  36706. get: function () {
  36707. return this._vignetteEnabled;
  36708. },
  36709. /**
  36710. * Sets wether the vignette effect is enabled.
  36711. */
  36712. set: function (value) {
  36713. if (this._vignetteEnabled === value) {
  36714. return;
  36715. }
  36716. this._vignetteEnabled = value;
  36717. this._updateParameters();
  36718. },
  36719. enumerable: true,
  36720. configurable: true
  36721. });
  36722. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  36723. /**
  36724. * Gets wether the image processing is applied through a post process or not.
  36725. */
  36726. get: function () {
  36727. return this._applyByPostProcess;
  36728. },
  36729. /**
  36730. * Sets wether the image processing is applied through a post process or not.
  36731. */
  36732. set: function (value) {
  36733. if (this._applyByPostProcess === value) {
  36734. return;
  36735. }
  36736. this._applyByPostProcess = value;
  36737. this._updateParameters();
  36738. },
  36739. enumerable: true,
  36740. configurable: true
  36741. });
  36742. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  36743. /**
  36744. * Gets wether the image processing is enabled or not.
  36745. */
  36746. get: function () {
  36747. return this._isEnabled;
  36748. },
  36749. /**
  36750. * Sets wether the image processing is enabled or not.
  36751. */
  36752. set: function (value) {
  36753. if (this._isEnabled === value) {
  36754. return;
  36755. }
  36756. this._isEnabled = value;
  36757. this._updateParameters();
  36758. },
  36759. enumerable: true,
  36760. configurable: true
  36761. });
  36762. /**
  36763. * Method called each time the image processing information changes requires to recompile the effect.
  36764. */
  36765. ImageProcessingConfiguration.prototype._updateParameters = function () {
  36766. this.onUpdateParameters.notifyObservers(this);
  36767. };
  36768. ImageProcessingConfiguration.prototype.getClassName = function () {
  36769. return "ImageProcessingConfiguration";
  36770. };
  36771. /**
  36772. * Prepare the list of uniforms associated with the Image Processing effects.
  36773. * @param uniformsList The list of uniforms used in the effect
  36774. * @param defines the list of defines currently in use
  36775. */
  36776. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  36777. if (defines.EXPOSURE) {
  36778. uniforms.push("exposureLinear");
  36779. }
  36780. if (defines.CONTRAST) {
  36781. uniforms.push("contrast");
  36782. }
  36783. if (defines.COLORGRADING) {
  36784. uniforms.push("colorTransformSettings");
  36785. }
  36786. if (defines.VIGNETTE) {
  36787. uniforms.push("vInverseScreenSize");
  36788. uniforms.push("vignetteSettings1");
  36789. uniforms.push("vignetteSettings2");
  36790. }
  36791. if (defines.COLORCURVES) {
  36792. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  36793. }
  36794. };
  36795. /**
  36796. * Prepare the list of samplers associated with the Image Processing effects.
  36797. * @param uniformsList The list of uniforms used in the effect
  36798. * @param defines the list of defines currently in use
  36799. */
  36800. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  36801. if (defines.COLORGRADING) {
  36802. samplersList.push("txColorTransform");
  36803. }
  36804. };
  36805. /**
  36806. * Prepare the list of defines associated to the shader.
  36807. * @param defines the list of defines to complete
  36808. */
  36809. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  36810. if (forPostProcess === void 0) { forPostProcess = false; }
  36811. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  36812. defines.VIGNETTE = false;
  36813. defines.TONEMAPPING = false;
  36814. defines.CONTRAST = false;
  36815. defines.EXPOSURE = false;
  36816. defines.COLORCURVES = false;
  36817. defines.COLORGRADING = false;
  36818. defines.COLORGRADING3D = false;
  36819. defines.IMAGEPROCESSING = false;
  36820. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  36821. return;
  36822. }
  36823. defines.VIGNETTE = this.vignetteEnabled;
  36824. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  36825. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  36826. defines.TONEMAPPING = this.toneMappingEnabled;
  36827. defines.CONTRAST = (this.contrast !== 1.0);
  36828. defines.EXPOSURE = (this.exposure !== 1.0);
  36829. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  36830. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  36831. if (defines.COLORGRADING) {
  36832. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  36833. }
  36834. else {
  36835. defines.COLORGRADING3D = false;
  36836. }
  36837. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  36838. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  36839. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  36840. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  36841. };
  36842. /**
  36843. * Returns true if all the image processing information are ready.
  36844. */
  36845. ImageProcessingConfiguration.prototype.isReady = function () {
  36846. // Color Grading texure can not be none blocking.
  36847. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  36848. };
  36849. /**
  36850. * Binds the image processing to the shader.
  36851. * @param effect The effect to bind to
  36852. */
  36853. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  36854. if (aspectRatio === void 0) { aspectRatio = 1; }
  36855. // Color Curves
  36856. if (this._colorCurvesEnabled && this.colorCurves) {
  36857. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  36858. }
  36859. // Vignette
  36860. if (this._vignetteEnabled) {
  36861. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  36862. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  36863. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  36864. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  36865. var vignetteScaleX = vignetteScaleY * aspectRatio;
  36866. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  36867. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  36868. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  36869. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  36870. var vignettePower = -2.0 * this.vignetteWeight;
  36871. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  36872. }
  36873. // Exposure
  36874. effect.setFloat("exposureLinear", this.exposure);
  36875. // Contrast
  36876. effect.setFloat("contrast", this.contrast);
  36877. // Color transform settings
  36878. if (this.colorGradingTexture) {
  36879. effect.setTexture("txColorTransform", this.colorGradingTexture);
  36880. var textureSize = this.colorGradingTexture.getSize().height;
  36881. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  36882. 0.5 / textureSize, // textureOffset
  36883. textureSize, // textureSize
  36884. this.colorGradingTexture.level // weight
  36885. );
  36886. }
  36887. };
  36888. /**
  36889. * Clones the current image processing instance.
  36890. * @return The cloned image processing
  36891. */
  36892. ImageProcessingConfiguration.prototype.clone = function () {
  36893. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  36894. };
  36895. /**
  36896. * Serializes the current image processing instance to a json representation.
  36897. * @return a JSON representation
  36898. */
  36899. ImageProcessingConfiguration.prototype.serialize = function () {
  36900. return BABYLON.SerializationHelper.Serialize(this);
  36901. };
  36902. /**
  36903. * Parses the image processing from a json representation.
  36904. * @param source the JSON source to parse
  36905. * @return The parsed image processing
  36906. */
  36907. ImageProcessingConfiguration.Parse = function (source) {
  36908. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  36909. };
  36910. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  36911. /**
  36912. * Used to apply the vignette as a mix with the pixel color.
  36913. */
  36914. get: function () {
  36915. return this._VIGNETTEMODE_MULTIPLY;
  36916. },
  36917. enumerable: true,
  36918. configurable: true
  36919. });
  36920. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  36921. /**
  36922. * Used to apply the vignette as a replacement of the pixel color.
  36923. */
  36924. get: function () {
  36925. return this._VIGNETTEMODE_OPAQUE;
  36926. },
  36927. enumerable: true,
  36928. configurable: true
  36929. });
  36930. // Static constants associated to the image processing.
  36931. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  36932. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  36933. __decorate([
  36934. BABYLON.serializeAsColorCurves()
  36935. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  36936. __decorate([
  36937. BABYLON.serialize()
  36938. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  36939. __decorate([
  36940. BABYLON.serializeAsTexture()
  36941. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  36942. __decorate([
  36943. BABYLON.serialize()
  36944. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  36945. __decorate([
  36946. BABYLON.serialize()
  36947. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  36948. __decorate([
  36949. BABYLON.serialize()
  36950. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  36951. __decorate([
  36952. BABYLON.serialize()
  36953. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  36954. __decorate([
  36955. BABYLON.serialize()
  36956. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  36957. __decorate([
  36958. BABYLON.serialize()
  36959. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  36960. __decorate([
  36961. BABYLON.serialize()
  36962. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  36963. __decorate([
  36964. BABYLON.serialize()
  36965. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  36966. __decorate([
  36967. BABYLON.serialize()
  36968. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  36969. __decorate([
  36970. BABYLON.serialize()
  36971. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  36972. __decorate([
  36973. BABYLON.serializeAsColor4()
  36974. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  36975. __decorate([
  36976. BABYLON.serialize()
  36977. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  36978. __decorate([
  36979. BABYLON.serialize()
  36980. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  36981. __decorate([
  36982. BABYLON.serialize()
  36983. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  36984. __decorate([
  36985. BABYLON.serialize()
  36986. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  36987. __decorate([
  36988. BABYLON.serialize()
  36989. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  36990. return ImageProcessingConfiguration;
  36991. }());
  36992. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  36993. })(BABYLON || (BABYLON = {}));
  36994. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  36995. var BABYLON;
  36996. (function (BABYLON) {
  36997. /**
  36998. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  36999. * It can help converting any input color in a desired output one. This can then be used to create effects
  37000. * from sepia, black and white to sixties or futuristic rendering...
  37001. *
  37002. * The only supported format is currently 3dl.
  37003. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37004. */
  37005. var ColorGradingTexture = /** @class */ (function (_super) {
  37006. __extends(ColorGradingTexture, _super);
  37007. /**
  37008. * Instantiates a ColorGradingTexture from the following parameters.
  37009. *
  37010. * @param url The location of the color gradind data (currently only supporting 3dl)
  37011. * @param scene The scene the texture will be used in
  37012. */
  37013. function ColorGradingTexture(url, scene) {
  37014. var _this = _super.call(this, scene) || this;
  37015. if (!url) {
  37016. return _this;
  37017. }
  37018. _this._engine = scene.getEngine();
  37019. _this._textureMatrix = BABYLON.Matrix.Identity();
  37020. _this.name = url;
  37021. _this.url = url;
  37022. _this.hasAlpha = false;
  37023. _this.isCube = false;
  37024. _this.is3D = _this._engine.webGLVersion > 1;
  37025. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37026. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37027. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37028. _this.anisotropicFilteringLevel = 1;
  37029. _this._texture = _this._getFromCache(url, true);
  37030. if (!_this._texture) {
  37031. if (!scene.useDelayedTextureLoading) {
  37032. _this.loadTexture();
  37033. }
  37034. else {
  37035. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37036. }
  37037. }
  37038. return _this;
  37039. }
  37040. /**
  37041. * Returns the texture matrix used in most of the material.
  37042. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37043. */
  37044. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37045. return this._textureMatrix;
  37046. };
  37047. /**
  37048. * Occurs when the file being loaded is a .3dl LUT file.
  37049. */
  37050. ColorGradingTexture.prototype.load3dlTexture = function () {
  37051. var engine = this._engine;
  37052. var texture;
  37053. if (engine.webGLVersion === 1) {
  37054. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37055. }
  37056. else {
  37057. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37058. }
  37059. this._texture = texture;
  37060. var callback = function (text) {
  37061. if (typeof text !== "string") {
  37062. return;
  37063. }
  37064. var data = null;
  37065. var tempData = null;
  37066. var line;
  37067. var lines = text.split('\n');
  37068. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37069. var maxColor = 0;
  37070. for (var i = 0; i < lines.length; i++) {
  37071. line = lines[i];
  37072. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37073. continue;
  37074. if (line.indexOf('#') === 0)
  37075. continue;
  37076. var words = line.split(" ");
  37077. if (size === 0) {
  37078. // Number of space + one
  37079. size = words.length;
  37080. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37081. tempData = new Float32Array(size * size * size * 4);
  37082. continue;
  37083. }
  37084. if (size != 0) {
  37085. var r = Math.max(parseInt(words[0]), 0);
  37086. var g = Math.max(parseInt(words[1]), 0);
  37087. var b = Math.max(parseInt(words[2]), 0);
  37088. maxColor = Math.max(r, maxColor);
  37089. maxColor = Math.max(g, maxColor);
  37090. maxColor = Math.max(b, maxColor);
  37091. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37092. if (tempData) {
  37093. tempData[pixelStorageIndex + 0] = r;
  37094. tempData[pixelStorageIndex + 1] = g;
  37095. tempData[pixelStorageIndex + 2] = b;
  37096. }
  37097. pixelIndexSlice++;
  37098. if (pixelIndexSlice % size == 0) {
  37099. pixelIndexH++;
  37100. pixelIndexSlice = 0;
  37101. if (pixelIndexH % size == 0) {
  37102. pixelIndexW++;
  37103. pixelIndexH = 0;
  37104. }
  37105. }
  37106. }
  37107. }
  37108. if (tempData && data) {
  37109. for (var i = 0; i < tempData.length; i++) {
  37110. if (i > 0 && (i + 1) % 4 === 0) {
  37111. data[i] = 255;
  37112. }
  37113. else {
  37114. var value = tempData[i];
  37115. data[i] = (value / maxColor * 255);
  37116. }
  37117. }
  37118. }
  37119. if (texture.is3D) {
  37120. texture.updateSize(size, size, size);
  37121. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37122. }
  37123. else {
  37124. texture.updateSize(size * size, size);
  37125. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37126. }
  37127. };
  37128. var scene = this.getScene();
  37129. if (scene) {
  37130. scene._loadFile(this.url, callback);
  37131. }
  37132. else {
  37133. this._engine._loadFile(this.url, callback);
  37134. }
  37135. return this._texture;
  37136. };
  37137. /**
  37138. * Starts the loading process of the texture.
  37139. */
  37140. ColorGradingTexture.prototype.loadTexture = function () {
  37141. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37142. this.load3dlTexture();
  37143. }
  37144. };
  37145. /**
  37146. * Clones the color gradind texture.
  37147. */
  37148. ColorGradingTexture.prototype.clone = function () {
  37149. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37150. // Base texture
  37151. newTexture.level = this.level;
  37152. return newTexture;
  37153. };
  37154. /**
  37155. * Called during delayed load for textures.
  37156. */
  37157. ColorGradingTexture.prototype.delayLoad = function () {
  37158. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37159. return;
  37160. }
  37161. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37162. this._texture = this._getFromCache(this.url, true);
  37163. if (!this._texture) {
  37164. this.loadTexture();
  37165. }
  37166. };
  37167. /**
  37168. * Parses a color grading texture serialized by Babylon.
  37169. * @param parsedTexture The texture information being parsedTexture
  37170. * @param scene The scene to load the texture in
  37171. * @param rootUrl The root url of the data assets to load
  37172. * @return A color gradind texture
  37173. */
  37174. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37175. var texture = null;
  37176. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37177. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37178. texture.name = parsedTexture.name;
  37179. texture.level = parsedTexture.level;
  37180. }
  37181. return texture;
  37182. };
  37183. /**
  37184. * Serializes the LUT texture to json format.
  37185. */
  37186. ColorGradingTexture.prototype.serialize = function () {
  37187. if (!this.name) {
  37188. return null;
  37189. }
  37190. var serializationObject = {};
  37191. serializationObject.name = this.name;
  37192. serializationObject.level = this.level;
  37193. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37194. return serializationObject;
  37195. };
  37196. /**
  37197. * Empty line regex stored for GC.
  37198. */
  37199. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37200. return ColorGradingTexture;
  37201. }(BABYLON.BaseTexture));
  37202. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37203. })(BABYLON || (BABYLON = {}));
  37204. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37205. var BABYLON;
  37206. (function (BABYLON) {
  37207. /**
  37208. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37209. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37210. * 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;
  37211. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37212. */
  37213. var ColorCurves = /** @class */ (function () {
  37214. function ColorCurves() {
  37215. this._dirty = true;
  37216. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37217. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37218. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37219. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37220. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37221. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37222. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37223. this._globalHue = 30;
  37224. this._globalDensity = 0;
  37225. this._globalSaturation = 0;
  37226. this._globalExposure = 0;
  37227. this._highlightsHue = 30;
  37228. this._highlightsDensity = 0;
  37229. this._highlightsSaturation = 0;
  37230. this._highlightsExposure = 0;
  37231. this._midtonesHue = 30;
  37232. this._midtonesDensity = 0;
  37233. this._midtonesSaturation = 0;
  37234. this._midtonesExposure = 0;
  37235. this._shadowsHue = 30;
  37236. this._shadowsDensity = 0;
  37237. this._shadowsSaturation = 0;
  37238. this._shadowsExposure = 0;
  37239. }
  37240. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37241. /**
  37242. * Gets the global Hue value.
  37243. * 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).
  37244. */
  37245. get: function () {
  37246. return this._globalHue;
  37247. },
  37248. /**
  37249. * Sets the global Hue value.
  37250. * 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).
  37251. */
  37252. set: function (value) {
  37253. this._globalHue = value;
  37254. this._dirty = true;
  37255. },
  37256. enumerable: true,
  37257. configurable: true
  37258. });
  37259. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37260. /**
  37261. * Gets the global Density value.
  37262. * 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.
  37263. * Values less than zero provide a filter of opposite hue.
  37264. */
  37265. get: function () {
  37266. return this._globalDensity;
  37267. },
  37268. /**
  37269. * Sets the global Density value.
  37270. * 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.
  37271. * Values less than zero provide a filter of opposite hue.
  37272. */
  37273. set: function (value) {
  37274. this._globalDensity = value;
  37275. this._dirty = true;
  37276. },
  37277. enumerable: true,
  37278. configurable: true
  37279. });
  37280. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37281. /**
  37282. * Gets the global Saturation value.
  37283. * 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.
  37284. */
  37285. get: function () {
  37286. return this._globalSaturation;
  37287. },
  37288. /**
  37289. * Sets the global Saturation value.
  37290. * 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.
  37291. */
  37292. set: function (value) {
  37293. this._globalSaturation = value;
  37294. this._dirty = true;
  37295. },
  37296. enumerable: true,
  37297. configurable: true
  37298. });
  37299. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37300. /**
  37301. * Gets the highlights Hue value.
  37302. * 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).
  37303. */
  37304. get: function () {
  37305. return this._highlightsHue;
  37306. },
  37307. /**
  37308. * Sets the highlights Hue value.
  37309. * 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).
  37310. */
  37311. set: function (value) {
  37312. this._highlightsHue = value;
  37313. this._dirty = true;
  37314. },
  37315. enumerable: true,
  37316. configurable: true
  37317. });
  37318. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37319. /**
  37320. * Gets the highlights Density value.
  37321. * 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.
  37322. * Values less than zero provide a filter of opposite hue.
  37323. */
  37324. get: function () {
  37325. return this._highlightsDensity;
  37326. },
  37327. /**
  37328. * Sets the highlights Density value.
  37329. * 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.
  37330. * Values less than zero provide a filter of opposite hue.
  37331. */
  37332. set: function (value) {
  37333. this._highlightsDensity = value;
  37334. this._dirty = true;
  37335. },
  37336. enumerable: true,
  37337. configurable: true
  37338. });
  37339. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37340. /**
  37341. * Gets the highlights Saturation value.
  37342. * 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.
  37343. */
  37344. get: function () {
  37345. return this._highlightsSaturation;
  37346. },
  37347. /**
  37348. * Sets the highlights Saturation value.
  37349. * 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.
  37350. */
  37351. set: function (value) {
  37352. this._highlightsSaturation = value;
  37353. this._dirty = true;
  37354. },
  37355. enumerable: true,
  37356. configurable: true
  37357. });
  37358. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37359. /**
  37360. * Gets the highlights Exposure value.
  37361. * 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.
  37362. */
  37363. get: function () {
  37364. return this._highlightsExposure;
  37365. },
  37366. /**
  37367. * Sets the highlights Exposure value.
  37368. * 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.
  37369. */
  37370. set: function (value) {
  37371. this._highlightsExposure = value;
  37372. this._dirty = true;
  37373. },
  37374. enumerable: true,
  37375. configurable: true
  37376. });
  37377. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37378. /**
  37379. * Gets the midtones Hue value.
  37380. * 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).
  37381. */
  37382. get: function () {
  37383. return this._midtonesHue;
  37384. },
  37385. /**
  37386. * Sets the midtones Hue value.
  37387. * 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).
  37388. */
  37389. set: function (value) {
  37390. this._midtonesHue = value;
  37391. this._dirty = true;
  37392. },
  37393. enumerable: true,
  37394. configurable: true
  37395. });
  37396. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37397. /**
  37398. * Gets the midtones Density value.
  37399. * 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.
  37400. * Values less than zero provide a filter of opposite hue.
  37401. */
  37402. get: function () {
  37403. return this._midtonesDensity;
  37404. },
  37405. /**
  37406. * Sets the midtones Density value.
  37407. * 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.
  37408. * Values less than zero provide a filter of opposite hue.
  37409. */
  37410. set: function (value) {
  37411. this._midtonesDensity = value;
  37412. this._dirty = true;
  37413. },
  37414. enumerable: true,
  37415. configurable: true
  37416. });
  37417. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37418. /**
  37419. * Gets the midtones Saturation value.
  37420. * 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.
  37421. */
  37422. get: function () {
  37423. return this._midtonesSaturation;
  37424. },
  37425. /**
  37426. * Sets the midtones Saturation value.
  37427. * 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.
  37428. */
  37429. set: function (value) {
  37430. this._midtonesSaturation = value;
  37431. this._dirty = true;
  37432. },
  37433. enumerable: true,
  37434. configurable: true
  37435. });
  37436. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37437. /**
  37438. * Gets the midtones Exposure value.
  37439. * 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.
  37440. */
  37441. get: function () {
  37442. return this._midtonesExposure;
  37443. },
  37444. /**
  37445. * Sets the midtones Exposure value.
  37446. * 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.
  37447. */
  37448. set: function (value) {
  37449. this._midtonesExposure = value;
  37450. this._dirty = true;
  37451. },
  37452. enumerable: true,
  37453. configurable: true
  37454. });
  37455. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37456. /**
  37457. * Gets the shadows Hue value.
  37458. * 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).
  37459. */
  37460. get: function () {
  37461. return this._shadowsHue;
  37462. },
  37463. /**
  37464. * Sets the shadows Hue value.
  37465. * 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).
  37466. */
  37467. set: function (value) {
  37468. this._shadowsHue = value;
  37469. this._dirty = true;
  37470. },
  37471. enumerable: true,
  37472. configurable: true
  37473. });
  37474. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37475. /**
  37476. * Gets the shadows Density value.
  37477. * 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.
  37478. * Values less than zero provide a filter of opposite hue.
  37479. */
  37480. get: function () {
  37481. return this._shadowsDensity;
  37482. },
  37483. /**
  37484. * Sets the shadows Density value.
  37485. * 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.
  37486. * Values less than zero provide a filter of opposite hue.
  37487. */
  37488. set: function (value) {
  37489. this._shadowsDensity = value;
  37490. this._dirty = true;
  37491. },
  37492. enumerable: true,
  37493. configurable: true
  37494. });
  37495. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37496. /**
  37497. * Gets the shadows Saturation value.
  37498. * 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.
  37499. */
  37500. get: function () {
  37501. return this._shadowsSaturation;
  37502. },
  37503. /**
  37504. * Sets the shadows Saturation value.
  37505. * 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.
  37506. */
  37507. set: function (value) {
  37508. this._shadowsSaturation = value;
  37509. this._dirty = true;
  37510. },
  37511. enumerable: true,
  37512. configurable: true
  37513. });
  37514. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37515. /**
  37516. * Gets the shadows Exposure value.
  37517. * 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.
  37518. */
  37519. get: function () {
  37520. return this._shadowsExposure;
  37521. },
  37522. /**
  37523. * Sets the shadows Exposure value.
  37524. * 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.
  37525. */
  37526. set: function (value) {
  37527. this._shadowsExposure = value;
  37528. this._dirty = true;
  37529. },
  37530. enumerable: true,
  37531. configurable: true
  37532. });
  37533. ColorCurves.prototype.getClassName = function () {
  37534. return "ColorCurves";
  37535. };
  37536. /**
  37537. * Binds the color curves to the shader.
  37538. * @param colorCurves The color curve to bind
  37539. * @param effect The effect to bind to
  37540. */
  37541. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37542. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37543. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37544. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37545. if (colorCurves._dirty) {
  37546. colorCurves._dirty = false;
  37547. // Fill in global info.
  37548. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37549. // Compute highlights info.
  37550. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37551. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37552. // Compute midtones info.
  37553. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37554. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37555. // Compute shadows info.
  37556. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37557. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37558. // Compute deltas (neutral is midtones).
  37559. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37560. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37561. }
  37562. if (effect) {
  37563. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37564. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37565. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37566. }
  37567. };
  37568. /**
  37569. * Prepare the list of uniforms associated with the ColorCurves effects.
  37570. * @param uniformsList The list of uniforms used in the effect
  37571. */
  37572. ColorCurves.PrepareUniforms = function (uniformsList) {
  37573. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37574. };
  37575. /**
  37576. * Returns color grading data based on a hue, density, saturation and exposure value.
  37577. * @param filterHue The hue of the color filter.
  37578. * @param filterDensity The density of the color filter.
  37579. * @param saturation The saturation.
  37580. * @param exposure The exposure.
  37581. * @param result The result data container.
  37582. */
  37583. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37584. if (hue == null) {
  37585. return;
  37586. }
  37587. hue = ColorCurves.clamp(hue, 0, 360);
  37588. density = ColorCurves.clamp(density, -100, 100);
  37589. saturation = ColorCurves.clamp(saturation, -100, 100);
  37590. exposure = ColorCurves.clamp(exposure, -100, 100);
  37591. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37592. // so that the maximum filter density is only 50% control. This provides fine control
  37593. // for small values and reasonable range.
  37594. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37595. density *= 0.5;
  37596. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37597. if (density < 0) {
  37598. density *= -1;
  37599. hue = (hue + 180) % 360;
  37600. }
  37601. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37602. result.scaleToRef(2, result);
  37603. result.a = 1 + 0.01 * saturation;
  37604. };
  37605. /**
  37606. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37607. * @param value The input slider value in range [-100,100].
  37608. * @returns Adjusted value.
  37609. */
  37610. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37611. value /= 100;
  37612. var x = Math.abs(value);
  37613. x = Math.pow(x, 2);
  37614. if (value < 0) {
  37615. x *= -1;
  37616. }
  37617. x *= 100;
  37618. return x;
  37619. };
  37620. /**
  37621. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37622. * @param hue The hue (H) input.
  37623. * @param saturation The saturation (S) input.
  37624. * @param brightness The brightness (B) input.
  37625. * @result An RGBA color represented as Vector4.
  37626. */
  37627. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37628. var h = ColorCurves.clamp(hue, 0, 360);
  37629. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37630. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37631. if (s === 0) {
  37632. result.r = v;
  37633. result.g = v;
  37634. result.b = v;
  37635. }
  37636. else {
  37637. // sector 0 to 5
  37638. h /= 60;
  37639. var i = Math.floor(h);
  37640. // fractional part of h
  37641. var f = h - i;
  37642. var p = v * (1 - s);
  37643. var q = v * (1 - s * f);
  37644. var t = v * (1 - s * (1 - f));
  37645. switch (i) {
  37646. case 0:
  37647. result.r = v;
  37648. result.g = t;
  37649. result.b = p;
  37650. break;
  37651. case 1:
  37652. result.r = q;
  37653. result.g = v;
  37654. result.b = p;
  37655. break;
  37656. case 2:
  37657. result.r = p;
  37658. result.g = v;
  37659. result.b = t;
  37660. break;
  37661. case 3:
  37662. result.r = p;
  37663. result.g = q;
  37664. result.b = v;
  37665. break;
  37666. case 4:
  37667. result.r = t;
  37668. result.g = p;
  37669. result.b = v;
  37670. break;
  37671. default:// case 5:
  37672. result.r = v;
  37673. result.g = p;
  37674. result.b = q;
  37675. break;
  37676. }
  37677. }
  37678. result.a = 1;
  37679. };
  37680. /**
  37681. * Returns a value clamped between min and max
  37682. * @param value The value to clamp
  37683. * @param min The minimum of value
  37684. * @param max The maximum of value
  37685. * @returns The clamped value.
  37686. */
  37687. ColorCurves.clamp = function (value, min, max) {
  37688. return Math.min(Math.max(value, min), max);
  37689. };
  37690. /**
  37691. * Clones the current color curve instance.
  37692. * @return The cloned curves
  37693. */
  37694. ColorCurves.prototype.clone = function () {
  37695. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  37696. };
  37697. /**
  37698. * Serializes the current color curve instance to a json representation.
  37699. * @return a JSON representation
  37700. */
  37701. ColorCurves.prototype.serialize = function () {
  37702. return BABYLON.SerializationHelper.Serialize(this);
  37703. };
  37704. /**
  37705. * Parses the color curve from a json representation.
  37706. * @param source the JSON source to parse
  37707. * @return The parsed curves
  37708. */
  37709. ColorCurves.Parse = function (source) {
  37710. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  37711. };
  37712. __decorate([
  37713. BABYLON.serialize()
  37714. ], ColorCurves.prototype, "_globalHue", void 0);
  37715. __decorate([
  37716. BABYLON.serialize()
  37717. ], ColorCurves.prototype, "_globalDensity", void 0);
  37718. __decorate([
  37719. BABYLON.serialize()
  37720. ], ColorCurves.prototype, "_globalSaturation", void 0);
  37721. __decorate([
  37722. BABYLON.serialize()
  37723. ], ColorCurves.prototype, "_globalExposure", void 0);
  37724. __decorate([
  37725. BABYLON.serialize()
  37726. ], ColorCurves.prototype, "_highlightsHue", void 0);
  37727. __decorate([
  37728. BABYLON.serialize()
  37729. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  37730. __decorate([
  37731. BABYLON.serialize()
  37732. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  37733. __decorate([
  37734. BABYLON.serialize()
  37735. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  37736. __decorate([
  37737. BABYLON.serialize()
  37738. ], ColorCurves.prototype, "_midtonesHue", void 0);
  37739. __decorate([
  37740. BABYLON.serialize()
  37741. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  37742. __decorate([
  37743. BABYLON.serialize()
  37744. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  37745. __decorate([
  37746. BABYLON.serialize()
  37747. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  37748. return ColorCurves;
  37749. }());
  37750. BABYLON.ColorCurves = ColorCurves;
  37751. })(BABYLON || (BABYLON = {}));
  37752. //# sourceMappingURL=babylon.colorCurves.js.map
  37753. //# sourceMappingURL=babylon.behavior.js.map
  37754. var BABYLON;
  37755. (function (BABYLON) {
  37756. /**
  37757. * "Static Class" containing the most commonly used helper while dealing with material for
  37758. * rendering purpose.
  37759. *
  37760. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  37761. *
  37762. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  37763. */
  37764. var MaterialHelper = /** @class */ (function () {
  37765. function MaterialHelper() {
  37766. }
  37767. /**
  37768. * Bind the current view position to an effect.
  37769. * @param effect The effect to be bound
  37770. * @param scene The scene the eyes position is used from
  37771. */
  37772. MaterialHelper.BindEyePosition = function (effect, scene) {
  37773. if (scene._forcedViewPosition) {
  37774. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  37775. return;
  37776. }
  37777. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37778. };
  37779. /**
  37780. * Helps preparing the defines values about the UVs in used in the effect.
  37781. * UVs are shared as much as we can accross chanels in the shaders.
  37782. * @param texture The texture we are preparing the UVs for
  37783. * @param defines The defines to update
  37784. * @param key The chanel key "diffuse", "specular"... used in the shader
  37785. */
  37786. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  37787. defines._needUVs = true;
  37788. defines[key] = true;
  37789. if (texture.getTextureMatrix().isIdentity(true)) {
  37790. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  37791. if (texture.coordinatesIndex === 0) {
  37792. defines["MAINUV1"] = true;
  37793. }
  37794. else {
  37795. defines["MAINUV2"] = true;
  37796. }
  37797. }
  37798. else {
  37799. defines[key + "DIRECTUV"] = 0;
  37800. }
  37801. };
  37802. /**
  37803. * Binds a texture matrix value to its corrsponding uniform
  37804. * @param texture The texture to bind the matrix for
  37805. * @param uniformBuffer The uniform buffer receivin the data
  37806. * @param key The chanel key "diffuse", "specular"... used in the shader
  37807. */
  37808. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  37809. var matrix = texture.getTextureMatrix();
  37810. if (!matrix.isIdentity(true)) {
  37811. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  37812. }
  37813. };
  37814. /**
  37815. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  37816. * @param mesh defines the current mesh
  37817. * @param scene defines the current scene
  37818. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  37819. * @param pointsCloud defines if point cloud rendering has to be turned on
  37820. * @param fogEnabled defines if fog has to be turned on
  37821. * @param alphaTest defines if alpha testing has to be turned on
  37822. * @param defines defines the current list of defines
  37823. */
  37824. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  37825. if (defines._areMiscDirty) {
  37826. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  37827. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  37828. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  37829. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  37830. defines["ALPHATEST"] = alphaTest;
  37831. }
  37832. };
  37833. /**
  37834. * Helper used to prepare the list of defines associated with frame values for shader compilation
  37835. * @param scene defines the current scene
  37836. * @param engine defines the current engine
  37837. * @param defines specifies the list of active defines
  37838. * @param useInstances defines if instances have to be turned on
  37839. * @param useClipPlane defines if clip plane have to be turned on
  37840. */
  37841. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  37842. if (useClipPlane === void 0) { useClipPlane = null; }
  37843. var changed = false;
  37844. if (useClipPlane == null) {
  37845. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  37846. }
  37847. if (defines["CLIPPLANE"] !== useClipPlane) {
  37848. defines["CLIPPLANE"] = useClipPlane;
  37849. changed = true;
  37850. }
  37851. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  37852. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  37853. changed = true;
  37854. }
  37855. if (defines["INSTANCES"] !== useInstances) {
  37856. defines["INSTANCES"] = useInstances;
  37857. changed = true;
  37858. }
  37859. if (changed) {
  37860. defines.markAsUnprocessed();
  37861. }
  37862. };
  37863. /**
  37864. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  37865. * @param mesh The mesh containing the geometry data we will draw
  37866. * @param defines The defines to update
  37867. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  37868. * @param useBones Precise whether bones should be used or not (override mesh info)
  37869. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  37870. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  37871. * @returns false if defines are considered not dirty and have not been checked
  37872. */
  37873. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  37874. if (useMorphTargets === void 0) { useMorphTargets = false; }
  37875. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  37876. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  37877. return false;
  37878. }
  37879. defines._normals = defines._needNormals;
  37880. defines._uvs = defines._needUVs;
  37881. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  37882. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37883. defines["TANGENT"] = true;
  37884. }
  37885. if (defines._needUVs) {
  37886. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  37887. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  37888. }
  37889. else {
  37890. defines["UV1"] = false;
  37891. defines["UV2"] = false;
  37892. }
  37893. if (useVertexColor) {
  37894. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  37895. defines["VERTEXCOLOR"] = hasVertexColors;
  37896. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  37897. }
  37898. if (useBones) {
  37899. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37900. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  37901. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  37902. }
  37903. else {
  37904. defines["NUM_BONE_INFLUENCERS"] = 0;
  37905. defines["BonesPerMesh"] = 0;
  37906. }
  37907. }
  37908. if (useMorphTargets) {
  37909. var manager = mesh.morphTargetManager;
  37910. if (manager) {
  37911. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  37912. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  37913. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  37914. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  37915. }
  37916. else {
  37917. defines["MORPHTARGETS_TANGENT"] = false;
  37918. defines["MORPHTARGETS_NORMAL"] = false;
  37919. defines["MORPHTARGETS"] = false;
  37920. defines["NUM_MORPH_INFLUENCERS"] = 0;
  37921. }
  37922. }
  37923. return true;
  37924. };
  37925. /**
  37926. * Prepares the defines related to the light information passed in parameter
  37927. * @param scene The scene we are intending to draw
  37928. * @param mesh The mesh the effect is compiling for
  37929. * @param defines The defines to update
  37930. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  37931. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  37932. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  37933. * @returns true if normals will be required for the rest of the effect
  37934. */
  37935. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  37936. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37937. if (disableLighting === void 0) { disableLighting = false; }
  37938. if (!defines._areLightsDirty) {
  37939. return defines._needNormals;
  37940. }
  37941. var lightIndex = 0;
  37942. var needNormals = false;
  37943. var needRebuild = false;
  37944. var lightmapMode = false;
  37945. var shadowEnabled = false;
  37946. var specularEnabled = false;
  37947. if (scene.lightsEnabled && !disableLighting) {
  37948. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  37949. var light = _a[_i];
  37950. needNormals = true;
  37951. if (defines["LIGHT" + lightIndex] === undefined) {
  37952. needRebuild = true;
  37953. }
  37954. defines["LIGHT" + lightIndex] = true;
  37955. defines["SPOTLIGHT" + lightIndex] = false;
  37956. defines["HEMILIGHT" + lightIndex] = false;
  37957. defines["POINTLIGHT" + lightIndex] = false;
  37958. defines["DIRLIGHT" + lightIndex] = false;
  37959. var type;
  37960. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  37961. type = "SPOTLIGHT" + lightIndex;
  37962. var spotLight = light;
  37963. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  37964. }
  37965. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  37966. type = "HEMILIGHT" + lightIndex;
  37967. }
  37968. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  37969. type = "POINTLIGHT" + lightIndex;
  37970. }
  37971. else {
  37972. type = "DIRLIGHT" + lightIndex;
  37973. }
  37974. defines[type] = true;
  37975. // Specular
  37976. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  37977. specularEnabled = true;
  37978. }
  37979. // Shadows
  37980. defines["SHADOW" + lightIndex] = false;
  37981. defines["SHADOWPCF" + lightIndex] = false;
  37982. defines["SHADOWESM" + lightIndex] = false;
  37983. defines["SHADOWCUBE" + lightIndex] = false;
  37984. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  37985. var shadowGenerator = light.getShadowGenerator();
  37986. if (shadowGenerator) {
  37987. shadowEnabled = true;
  37988. shadowGenerator.prepareDefines(defines, lightIndex);
  37989. }
  37990. }
  37991. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  37992. lightmapMode = true;
  37993. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  37994. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  37995. }
  37996. else {
  37997. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  37998. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  37999. }
  38000. lightIndex++;
  38001. if (lightIndex === maxSimultaneousLights)
  38002. break;
  38003. }
  38004. }
  38005. defines["SPECULARTERM"] = specularEnabled;
  38006. defines["SHADOWS"] = shadowEnabled;
  38007. // Resetting all other lights if any
  38008. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38009. if (defines["LIGHT" + index] !== undefined) {
  38010. defines["LIGHT" + index] = false;
  38011. defines["HEMILIGHT" + lightIndex] = false;
  38012. defines["POINTLIGHT" + lightIndex] = false;
  38013. defines["DIRLIGHT" + lightIndex] = false;
  38014. defines["SPOTLIGHT" + lightIndex] = false;
  38015. defines["SHADOW" + lightIndex] = false;
  38016. }
  38017. }
  38018. var caps = scene.getEngine().getCaps();
  38019. if (defines["SHADOWFLOAT"] === undefined) {
  38020. needRebuild = true;
  38021. }
  38022. defines["SHADOWFLOAT"] = shadowEnabled &&
  38023. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38024. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38025. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38026. if (needRebuild) {
  38027. defines.rebuild();
  38028. }
  38029. return needNormals;
  38030. };
  38031. /**
  38032. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38033. * that won t be acctive due to defines being turned off.
  38034. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38035. * @param samplersList The samplers list
  38036. * @param defines The defines helping in the list generation
  38037. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38038. */
  38039. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38040. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38041. var uniformsList;
  38042. var uniformBuffersList = null;
  38043. if (uniformsListOrOptions.uniformsNames) {
  38044. var options = uniformsListOrOptions;
  38045. uniformsList = options.uniformsNames;
  38046. uniformBuffersList = options.uniformBuffersNames;
  38047. samplersList = options.samplers;
  38048. defines = options.defines;
  38049. maxSimultaneousLights = options.maxSimultaneousLights;
  38050. }
  38051. else {
  38052. uniformsList = uniformsListOrOptions;
  38053. if (!samplersList) {
  38054. samplersList = [];
  38055. }
  38056. }
  38057. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38058. if (!defines["LIGHT" + lightIndex]) {
  38059. break;
  38060. }
  38061. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38062. if (uniformBuffersList) {
  38063. uniformBuffersList.push("Light" + lightIndex);
  38064. }
  38065. samplersList.push("shadowSampler" + lightIndex);
  38066. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38067. samplersList.push("projectionLightSampler" + lightIndex);
  38068. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38069. }
  38070. }
  38071. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38072. uniformsList.push("morphTargetInfluences");
  38073. }
  38074. };
  38075. /**
  38076. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38077. * @param defines The defines to update while falling back
  38078. * @param fallbacks The authorized effect fallbacks
  38079. * @param maxSimultaneousLights The maximum number of lights allowed
  38080. * @param rank the current rank of the Effect
  38081. * @returns The newly affected rank
  38082. */
  38083. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38084. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38085. if (rank === void 0) { rank = 0; }
  38086. var lightFallbackRank = 0;
  38087. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38088. if (!defines["LIGHT" + lightIndex]) {
  38089. break;
  38090. }
  38091. if (lightIndex > 0) {
  38092. lightFallbackRank = rank + lightIndex;
  38093. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38094. }
  38095. if (!defines["SHADOWS"]) {
  38096. if (defines["SHADOW" + lightIndex]) {
  38097. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38098. }
  38099. if (defines["SHADOWPCF" + lightIndex]) {
  38100. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38101. }
  38102. if (defines["SHADOWESM" + lightIndex]) {
  38103. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38104. }
  38105. }
  38106. }
  38107. return lightFallbackRank++;
  38108. };
  38109. /**
  38110. * Prepares the list of attributes required for morph targets according to the effect defines.
  38111. * @param attribs The current list of supported attribs
  38112. * @param mesh The mesh to prepare the morph targets attributes for
  38113. * @param defines The current Defines of the effect
  38114. */
  38115. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38116. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38117. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38118. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38119. var manager = mesh.morphTargetManager;
  38120. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38121. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38122. for (var index = 0; index < influencers; index++) {
  38123. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38124. if (normal) {
  38125. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38126. }
  38127. if (tangent) {
  38128. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38129. }
  38130. if (attribs.length > maxAttributesCount) {
  38131. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38132. }
  38133. }
  38134. }
  38135. };
  38136. /**
  38137. * Prepares the list of attributes required for bones according to the effect defines.
  38138. * @param attribs The current list of supported attribs
  38139. * @param mesh The mesh to prepare the bones attributes for
  38140. * @param defines The current Defines of the effect
  38141. * @param fallbacks The current efffect fallback strategy
  38142. */
  38143. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38144. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38145. fallbacks.addCPUSkinningFallback(0, mesh);
  38146. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38147. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38148. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38149. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38150. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38151. }
  38152. }
  38153. };
  38154. /**
  38155. * Prepares the list of attributes required for instances according to the effect defines.
  38156. * @param attribs The current list of supported attribs
  38157. * @param defines The current Defines of the effect
  38158. */
  38159. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38160. if (defines["INSTANCES"]) {
  38161. attribs.push("world0");
  38162. attribs.push("world1");
  38163. attribs.push("world2");
  38164. attribs.push("world3");
  38165. }
  38166. };
  38167. /**
  38168. * Binds the light shadow information to the effect for the given mesh.
  38169. * @param light The light containing the generator
  38170. * @param scene The scene the lights belongs to
  38171. * @param mesh The mesh we are binding the information to render
  38172. * @param lightIndex The light index in the effect used to render the mesh
  38173. * @param effect The effect we are binding the data to
  38174. */
  38175. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38176. if (light.shadowEnabled && mesh.receiveShadows) {
  38177. var shadowGenerator = light.getShadowGenerator();
  38178. if (shadowGenerator) {
  38179. shadowGenerator.bindShadowLight(lightIndex, effect);
  38180. }
  38181. }
  38182. };
  38183. /**
  38184. * Binds the light information to the effect.
  38185. * @param light The light containing the generator
  38186. * @param effect The effect we are binding the data to
  38187. * @param lightIndex The light index in the effect used to render
  38188. */
  38189. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38190. light.transferToEffect(effect, lightIndex + "");
  38191. };
  38192. /**
  38193. * Binds the lights information from the scene to the effect for the given mesh.
  38194. * @param scene The scene the lights belongs to
  38195. * @param mesh The mesh we are binding the information to render
  38196. * @param effect The effect we are binding the data to
  38197. * @param defines The generated defines for the effect
  38198. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38199. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38200. */
  38201. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38202. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38203. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38204. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38205. for (var i = 0; i < len; i++) {
  38206. var light = mesh._lightSources[i];
  38207. var iAsString = i.toString();
  38208. var scaledIntensity = light.getScaledIntensity();
  38209. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38210. MaterialHelper.BindLightProperties(light, effect, i);
  38211. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38212. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38213. if (defines["SPECULARTERM"]) {
  38214. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38215. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38216. }
  38217. // Shadows
  38218. if (scene.shadowsEnabled) {
  38219. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38220. }
  38221. light._uniformBuffer.update();
  38222. }
  38223. };
  38224. /**
  38225. * Binds the fog information from the scene to the effect for the given mesh.
  38226. * @param scene The scene the lights belongs to
  38227. * @param mesh The mesh we are binding the information to render
  38228. * @param effect The effect we are binding the data to
  38229. */
  38230. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38231. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38232. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38233. effect.setColor3("vFogColor", scene.fogColor);
  38234. }
  38235. };
  38236. /**
  38237. * Binds the bones information from the mesh to the effect.
  38238. * @param mesh The mesh we are binding the information to render
  38239. * @param effect The effect we are binding the data to
  38240. */
  38241. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38242. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38243. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38244. if (matrices && effect) {
  38245. effect.setMatrices("mBones", matrices);
  38246. }
  38247. }
  38248. };
  38249. /**
  38250. * Binds the morph targets information from the mesh to the effect.
  38251. * @param abstractMesh The mesh we are binding the information to render
  38252. * @param effect The effect we are binding the data to
  38253. */
  38254. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38255. var manager = abstractMesh.morphTargetManager;
  38256. if (!abstractMesh || !manager) {
  38257. return;
  38258. }
  38259. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38260. };
  38261. /**
  38262. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38263. * @param defines The generated defines used in the effect
  38264. * @param effect The effect we are binding the data to
  38265. * @param scene The scene we are willing to render with logarithmic scale for
  38266. */
  38267. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38268. if (defines["LOGARITHMICDEPTH"]) {
  38269. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38270. }
  38271. };
  38272. /**
  38273. * Binds the clip plane information from the scene to the effect.
  38274. * @param scene The scene the clip plane information are extracted from
  38275. * @param effect The effect we are binding the data to
  38276. */
  38277. MaterialHelper.BindClipPlane = function (effect, scene) {
  38278. if (scene.clipPlane) {
  38279. var clipPlane = scene.clipPlane;
  38280. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38281. }
  38282. };
  38283. return MaterialHelper;
  38284. }());
  38285. BABYLON.MaterialHelper = MaterialHelper;
  38286. })(BABYLON || (BABYLON = {}));
  38287. //# sourceMappingURL=babylon.materialHelper.js.map
  38288. var BABYLON;
  38289. (function (BABYLON) {
  38290. var PushMaterial = /** @class */ (function (_super) {
  38291. __extends(PushMaterial, _super);
  38292. function PushMaterial(name, scene) {
  38293. var _this = _super.call(this, name, scene) || this;
  38294. _this._normalMatrix = new BABYLON.Matrix();
  38295. _this.storeEffectOnSubMeshes = true;
  38296. return _this;
  38297. }
  38298. PushMaterial.prototype.getEffect = function () {
  38299. return this._activeEffect;
  38300. };
  38301. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38302. if (!mesh) {
  38303. return false;
  38304. }
  38305. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38306. return true;
  38307. }
  38308. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38309. };
  38310. /**
  38311. * Binds the given world matrix to the active effect
  38312. *
  38313. * @param world the matrix to bind
  38314. */
  38315. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38316. this._activeEffect.setMatrix("world", world);
  38317. };
  38318. /**
  38319. * Binds the given normal matrix to the active effect
  38320. *
  38321. * @param normalMatrix the matrix to bind
  38322. */
  38323. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38324. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38325. };
  38326. PushMaterial.prototype.bind = function (world, mesh) {
  38327. if (!mesh) {
  38328. return;
  38329. }
  38330. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38331. };
  38332. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38333. if (effect === void 0) { effect = null; }
  38334. _super.prototype._afterBind.call(this, mesh);
  38335. this.getScene()._cachedEffect = effect;
  38336. };
  38337. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38338. if (visibility === void 0) { visibility = 1; }
  38339. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38340. };
  38341. return PushMaterial;
  38342. }(BABYLON.Material));
  38343. BABYLON.PushMaterial = PushMaterial;
  38344. })(BABYLON || (BABYLON = {}));
  38345. //# sourceMappingURL=babylon.pushMaterial.js.map
  38346. var BABYLON;
  38347. (function (BABYLON) {
  38348. /** @ignore */
  38349. var StandardMaterialDefines = /** @class */ (function (_super) {
  38350. __extends(StandardMaterialDefines, _super);
  38351. function StandardMaterialDefines() {
  38352. var _this = _super.call(this) || this;
  38353. _this.MAINUV1 = false;
  38354. _this.MAINUV2 = false;
  38355. _this.DIFFUSE = false;
  38356. _this.DIFFUSEDIRECTUV = 0;
  38357. _this.AMBIENT = false;
  38358. _this.AMBIENTDIRECTUV = 0;
  38359. _this.OPACITY = false;
  38360. _this.OPACITYDIRECTUV = 0;
  38361. _this.OPACITYRGB = false;
  38362. _this.REFLECTION = false;
  38363. _this.EMISSIVE = false;
  38364. _this.EMISSIVEDIRECTUV = 0;
  38365. _this.SPECULAR = false;
  38366. _this.SPECULARDIRECTUV = 0;
  38367. _this.BUMP = false;
  38368. _this.BUMPDIRECTUV = 0;
  38369. _this.PARALLAX = false;
  38370. _this.PARALLAXOCCLUSION = false;
  38371. _this.SPECULAROVERALPHA = false;
  38372. _this.CLIPPLANE = false;
  38373. _this.ALPHATEST = false;
  38374. _this.DEPTHPREPASS = false;
  38375. _this.ALPHAFROMDIFFUSE = false;
  38376. _this.POINTSIZE = false;
  38377. _this.FOG = false;
  38378. _this.SPECULARTERM = false;
  38379. _this.DIFFUSEFRESNEL = false;
  38380. _this.OPACITYFRESNEL = false;
  38381. _this.REFLECTIONFRESNEL = false;
  38382. _this.REFRACTIONFRESNEL = false;
  38383. _this.EMISSIVEFRESNEL = false;
  38384. _this.FRESNEL = false;
  38385. _this.NORMAL = false;
  38386. _this.UV1 = false;
  38387. _this.UV2 = false;
  38388. _this.VERTEXCOLOR = false;
  38389. _this.VERTEXALPHA = false;
  38390. _this.NUM_BONE_INFLUENCERS = 0;
  38391. _this.BonesPerMesh = 0;
  38392. _this.INSTANCES = false;
  38393. _this.GLOSSINESS = false;
  38394. _this.ROUGHNESS = false;
  38395. _this.EMISSIVEASILLUMINATION = false;
  38396. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38397. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38398. _this.LIGHTMAP = false;
  38399. _this.LIGHTMAPDIRECTUV = 0;
  38400. _this.OBJECTSPACE_NORMALMAP = false;
  38401. _this.USELIGHTMAPASSHADOWMAP = false;
  38402. _this.REFLECTIONMAP_3D = false;
  38403. _this.REFLECTIONMAP_SPHERICAL = false;
  38404. _this.REFLECTIONMAP_PLANAR = false;
  38405. _this.REFLECTIONMAP_CUBIC = false;
  38406. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38407. _this.REFLECTIONMAP_PROJECTION = false;
  38408. _this.REFLECTIONMAP_SKYBOX = false;
  38409. _this.REFLECTIONMAP_EXPLICIT = false;
  38410. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38411. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38412. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38413. _this.INVERTCUBICMAP = false;
  38414. _this.LOGARITHMICDEPTH = false;
  38415. _this.REFRACTION = false;
  38416. _this.REFRACTIONMAP_3D = false;
  38417. _this.REFLECTIONOVERALPHA = false;
  38418. _this.TWOSIDEDLIGHTING = false;
  38419. _this.SHADOWFLOAT = false;
  38420. _this.MORPHTARGETS = false;
  38421. _this.MORPHTARGETS_NORMAL = false;
  38422. _this.MORPHTARGETS_TANGENT = false;
  38423. _this.NUM_MORPH_INFLUENCERS = 0;
  38424. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38425. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38426. _this.IMAGEPROCESSING = false;
  38427. _this.VIGNETTE = false;
  38428. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38429. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38430. _this.TONEMAPPING = false;
  38431. _this.CONTRAST = false;
  38432. _this.COLORCURVES = false;
  38433. _this.COLORGRADING = false;
  38434. _this.COLORGRADING3D = false;
  38435. _this.SAMPLER3DGREENDEPTH = false;
  38436. _this.SAMPLER3DBGRMAP = false;
  38437. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38438. _this.EXPOSURE = false;
  38439. _this.rebuild();
  38440. return _this;
  38441. }
  38442. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38443. var modes = [
  38444. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38445. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38446. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38447. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38448. ];
  38449. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38450. var mode = modes_1[_i];
  38451. this[mode] = (mode === modeToEnable);
  38452. }
  38453. };
  38454. return StandardMaterialDefines;
  38455. }(BABYLON.MaterialDefines));
  38456. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38457. var StandardMaterial = /** @class */ (function (_super) {
  38458. __extends(StandardMaterial, _super);
  38459. function StandardMaterial(name, scene) {
  38460. var _this = _super.call(this, name, scene) || this;
  38461. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38462. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38463. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38464. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38465. _this.specularPower = 64;
  38466. _this._useAlphaFromDiffuseTexture = false;
  38467. _this._useEmissiveAsIllumination = false;
  38468. _this._linkEmissiveWithDiffuse = false;
  38469. _this._useSpecularOverAlpha = false;
  38470. _this._useReflectionOverAlpha = false;
  38471. _this._disableLighting = false;
  38472. _this._useObjectSpaceNormalMap = false;
  38473. _this._useParallax = false;
  38474. _this._useParallaxOcclusion = false;
  38475. _this.parallaxScaleBias = 0.05;
  38476. _this._roughness = 0;
  38477. _this.indexOfRefraction = 0.98;
  38478. _this.invertRefractionY = true;
  38479. _this._useLightmapAsShadowmap = false;
  38480. _this._useReflectionFresnelFromSpecular = false;
  38481. _this._useGlossinessFromSpecularMapAlpha = false;
  38482. _this._maxSimultaneousLights = 4;
  38483. /**
  38484. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38485. */
  38486. _this._invertNormalMapX = false;
  38487. /**
  38488. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38489. */
  38490. _this._invertNormalMapY = false;
  38491. /**
  38492. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38493. */
  38494. _this._twoSidedLighting = false;
  38495. _this._renderTargets = new BABYLON.SmartArray(16);
  38496. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38497. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38498. // Setup the default processing configuration to the scene.
  38499. _this._attachImageProcessingConfiguration(null);
  38500. _this.getRenderTargetTextures = function () {
  38501. _this._renderTargets.reset();
  38502. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38503. _this._renderTargets.push(_this._reflectionTexture);
  38504. }
  38505. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38506. _this._renderTargets.push(_this._refractionTexture);
  38507. }
  38508. return _this._renderTargets;
  38509. };
  38510. return _this;
  38511. }
  38512. ;
  38513. ;
  38514. ;
  38515. ;
  38516. ;
  38517. ;
  38518. ;
  38519. ;
  38520. ;
  38521. ;
  38522. ;
  38523. ;
  38524. ;
  38525. ;
  38526. ;
  38527. ;
  38528. ;
  38529. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38530. /**
  38531. * Gets the image processing configuration used either in this material.
  38532. */
  38533. get: function () {
  38534. return this._imageProcessingConfiguration;
  38535. },
  38536. /**
  38537. * Sets the Default image processing configuration used either in the this material.
  38538. *
  38539. * If sets to null, the scene one is in use.
  38540. */
  38541. set: function (value) {
  38542. this._attachImageProcessingConfiguration(value);
  38543. // Ensure the effect will be rebuilt.
  38544. this._markAllSubMeshesAsTexturesDirty();
  38545. },
  38546. enumerable: true,
  38547. configurable: true
  38548. });
  38549. /**
  38550. * Attaches a new image processing configuration to the Standard Material.
  38551. * @param configuration
  38552. */
  38553. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38554. var _this = this;
  38555. if (configuration === this._imageProcessingConfiguration) {
  38556. return;
  38557. }
  38558. // Detaches observer.
  38559. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38560. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38561. }
  38562. // Pick the scene configuration if needed.
  38563. if (!configuration) {
  38564. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38565. }
  38566. else {
  38567. this._imageProcessingConfiguration = configuration;
  38568. }
  38569. // Attaches observer.
  38570. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38571. _this._markAllSubMeshesAsImageProcessingDirty();
  38572. });
  38573. };
  38574. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38575. /**
  38576. * Gets wether the color curves effect is enabled.
  38577. */
  38578. get: function () {
  38579. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38580. },
  38581. /**
  38582. * Sets wether the color curves effect is enabled.
  38583. */
  38584. set: function (value) {
  38585. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38586. },
  38587. enumerable: true,
  38588. configurable: true
  38589. });
  38590. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38591. /**
  38592. * Gets wether the color grading effect is enabled.
  38593. */
  38594. get: function () {
  38595. return this.imageProcessingConfiguration.colorGradingEnabled;
  38596. },
  38597. /**
  38598. * Gets wether the color grading effect is enabled.
  38599. */
  38600. set: function (value) {
  38601. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38602. },
  38603. enumerable: true,
  38604. configurable: true
  38605. });
  38606. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38607. /**
  38608. * Gets wether tonemapping is enabled or not.
  38609. */
  38610. get: function () {
  38611. return this._imageProcessingConfiguration.toneMappingEnabled;
  38612. },
  38613. /**
  38614. * Sets wether tonemapping is enabled or not
  38615. */
  38616. set: function (value) {
  38617. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38618. },
  38619. enumerable: true,
  38620. configurable: true
  38621. });
  38622. ;
  38623. ;
  38624. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38625. /**
  38626. * The camera exposure used on this material.
  38627. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38628. * This corresponds to a photographic exposure.
  38629. */
  38630. get: function () {
  38631. return this._imageProcessingConfiguration.exposure;
  38632. },
  38633. /**
  38634. * The camera exposure used on this material.
  38635. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38636. * This corresponds to a photographic exposure.
  38637. */
  38638. set: function (value) {
  38639. this._imageProcessingConfiguration.exposure = value;
  38640. },
  38641. enumerable: true,
  38642. configurable: true
  38643. });
  38644. ;
  38645. ;
  38646. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38647. /**
  38648. * Gets The camera contrast used on this material.
  38649. */
  38650. get: function () {
  38651. return this._imageProcessingConfiguration.contrast;
  38652. },
  38653. /**
  38654. * Sets The camera contrast used on this material.
  38655. */
  38656. set: function (value) {
  38657. this._imageProcessingConfiguration.contrast = value;
  38658. },
  38659. enumerable: true,
  38660. configurable: true
  38661. });
  38662. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38663. /**
  38664. * Gets the Color Grading 2D Lookup Texture.
  38665. */
  38666. get: function () {
  38667. return this._imageProcessingConfiguration.colorGradingTexture;
  38668. },
  38669. /**
  38670. * Sets the Color Grading 2D Lookup Texture.
  38671. */
  38672. set: function (value) {
  38673. this._imageProcessingConfiguration.colorGradingTexture = value;
  38674. },
  38675. enumerable: true,
  38676. configurable: true
  38677. });
  38678. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  38679. /**
  38680. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38681. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38682. * 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;
  38683. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38684. */
  38685. get: function () {
  38686. return this._imageProcessingConfiguration.colorCurves;
  38687. },
  38688. /**
  38689. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38690. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38691. * 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;
  38692. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38693. */
  38694. set: function (value) {
  38695. this._imageProcessingConfiguration.colorCurves = value;
  38696. },
  38697. enumerable: true,
  38698. configurable: true
  38699. });
  38700. StandardMaterial.prototype.getClassName = function () {
  38701. return "StandardMaterial";
  38702. };
  38703. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  38704. get: function () {
  38705. return this._useLogarithmicDepth;
  38706. },
  38707. set: function (value) {
  38708. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38709. this._markAllSubMeshesAsMiscDirty();
  38710. },
  38711. enumerable: true,
  38712. configurable: true
  38713. });
  38714. StandardMaterial.prototype.needAlphaBlending = function () {
  38715. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38716. };
  38717. StandardMaterial.prototype.needAlphaTesting = function () {
  38718. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  38719. };
  38720. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  38721. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  38722. };
  38723. StandardMaterial.prototype.getAlphaTestTexture = function () {
  38724. return this._diffuseTexture;
  38725. };
  38726. /**
  38727. * Child classes can use it to update shaders
  38728. */
  38729. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38730. if (useInstances === void 0) { useInstances = false; }
  38731. if (subMesh.effect && this.isFrozen) {
  38732. if (this._wasPreviouslyReady && subMesh.effect) {
  38733. return true;
  38734. }
  38735. }
  38736. if (!subMesh._materialDefines) {
  38737. subMesh._materialDefines = new StandardMaterialDefines();
  38738. }
  38739. var scene = this.getScene();
  38740. var defines = subMesh._materialDefines;
  38741. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38742. if (defines._renderId === scene.getRenderId()) {
  38743. return true;
  38744. }
  38745. }
  38746. var engine = scene.getEngine();
  38747. // Lights
  38748. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38749. // Textures
  38750. if (defines._areTexturesDirty) {
  38751. defines._needUVs = false;
  38752. defines.MAINUV1 = false;
  38753. defines.MAINUV2 = false;
  38754. if (scene.texturesEnabled) {
  38755. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38756. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  38757. return false;
  38758. }
  38759. else {
  38760. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  38761. }
  38762. }
  38763. else {
  38764. defines.DIFFUSE = false;
  38765. }
  38766. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38767. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38768. return false;
  38769. }
  38770. else {
  38771. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38772. }
  38773. }
  38774. else {
  38775. defines.AMBIENT = false;
  38776. }
  38777. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38778. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38779. return false;
  38780. }
  38781. else {
  38782. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38783. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38784. }
  38785. }
  38786. else {
  38787. defines.OPACITY = false;
  38788. }
  38789. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38790. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  38791. return false;
  38792. }
  38793. else {
  38794. defines._needNormals = true;
  38795. defines.REFLECTION = true;
  38796. defines.ROUGHNESS = (this._roughness > 0);
  38797. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  38798. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  38799. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  38800. switch (this._reflectionTexture.coordinatesMode) {
  38801. case BABYLON.Texture.CUBIC_MODE:
  38802. case BABYLON.Texture.INVCUBIC_MODE:
  38803. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  38804. break;
  38805. case BABYLON.Texture.EXPLICIT_MODE:
  38806. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  38807. break;
  38808. case BABYLON.Texture.PLANAR_MODE:
  38809. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  38810. break;
  38811. case BABYLON.Texture.PROJECTION_MODE:
  38812. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  38813. break;
  38814. case BABYLON.Texture.SKYBOX_MODE:
  38815. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  38816. break;
  38817. case BABYLON.Texture.SPHERICAL_MODE:
  38818. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  38819. break;
  38820. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38821. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  38822. break;
  38823. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38824. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  38825. break;
  38826. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38827. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  38828. break;
  38829. }
  38830. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  38831. }
  38832. }
  38833. else {
  38834. defines.REFLECTION = false;
  38835. }
  38836. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38837. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38838. return false;
  38839. }
  38840. else {
  38841. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38842. }
  38843. }
  38844. else {
  38845. defines.EMISSIVE = false;
  38846. }
  38847. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38848. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38849. return false;
  38850. }
  38851. else {
  38852. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38853. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38854. }
  38855. }
  38856. else {
  38857. defines.LIGHTMAP = false;
  38858. }
  38859. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38860. if (!this._specularTexture.isReadyOrNotBlocking()) {
  38861. return false;
  38862. }
  38863. else {
  38864. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  38865. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  38866. }
  38867. }
  38868. else {
  38869. defines.SPECULAR = false;
  38870. }
  38871. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  38872. // Bump texure can not be not blocking.
  38873. if (!this._bumpTexture.isReady()) {
  38874. return false;
  38875. }
  38876. else {
  38877. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38878. defines.PARALLAX = this._useParallax;
  38879. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  38880. }
  38881. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  38882. }
  38883. else {
  38884. defines.BUMP = false;
  38885. }
  38886. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38887. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38888. return false;
  38889. }
  38890. else {
  38891. defines._needUVs = true;
  38892. defines.REFRACTION = true;
  38893. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38894. }
  38895. }
  38896. else {
  38897. defines.REFRACTION = false;
  38898. }
  38899. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  38900. }
  38901. else {
  38902. defines.DIFFUSE = false;
  38903. defines.AMBIENT = false;
  38904. defines.OPACITY = false;
  38905. defines.REFLECTION = false;
  38906. defines.EMISSIVE = false;
  38907. defines.LIGHTMAP = false;
  38908. defines.BUMP = false;
  38909. defines.REFRACTION = false;
  38910. }
  38911. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  38912. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  38913. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  38914. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38915. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38916. }
  38917. if (defines._areImageProcessingDirty) {
  38918. if (!this._imageProcessingConfiguration.isReady()) {
  38919. return false;
  38920. }
  38921. this._imageProcessingConfiguration.prepareDefines(defines);
  38922. }
  38923. if (defines._areFresnelDirty) {
  38924. if (StandardMaterial.FresnelEnabled) {
  38925. // Fresnel
  38926. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  38927. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  38928. this._reflectionFresnelParameters) {
  38929. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  38930. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  38931. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  38932. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  38933. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  38934. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  38935. defines._needNormals = true;
  38936. defines.FRESNEL = true;
  38937. }
  38938. }
  38939. else {
  38940. defines.FRESNEL = false;
  38941. }
  38942. }
  38943. // Misc.
  38944. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  38945. // Attribs
  38946. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  38947. // Values that need to be evaluated on every frame
  38948. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  38949. // Get correct effect
  38950. if (defines.isDirty) {
  38951. defines.markAsProcessed();
  38952. scene.resetCachedMaterial();
  38953. // Fallbacks
  38954. var fallbacks = new BABYLON.EffectFallbacks();
  38955. if (defines.REFLECTION) {
  38956. fallbacks.addFallback(0, "REFLECTION");
  38957. }
  38958. if (defines.SPECULAR) {
  38959. fallbacks.addFallback(0, "SPECULAR");
  38960. }
  38961. if (defines.BUMP) {
  38962. fallbacks.addFallback(0, "BUMP");
  38963. }
  38964. if (defines.PARALLAX) {
  38965. fallbacks.addFallback(1, "PARALLAX");
  38966. }
  38967. if (defines.PARALLAXOCCLUSION) {
  38968. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38969. }
  38970. if (defines.SPECULAROVERALPHA) {
  38971. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38972. }
  38973. if (defines.FOG) {
  38974. fallbacks.addFallback(1, "FOG");
  38975. }
  38976. if (defines.POINTSIZE) {
  38977. fallbacks.addFallback(0, "POINTSIZE");
  38978. }
  38979. if (defines.LOGARITHMICDEPTH) {
  38980. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38981. }
  38982. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  38983. if (defines.SPECULARTERM) {
  38984. fallbacks.addFallback(0, "SPECULARTERM");
  38985. }
  38986. if (defines.DIFFUSEFRESNEL) {
  38987. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  38988. }
  38989. if (defines.OPACITYFRESNEL) {
  38990. fallbacks.addFallback(2, "OPACITYFRESNEL");
  38991. }
  38992. if (defines.REFLECTIONFRESNEL) {
  38993. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  38994. }
  38995. if (defines.EMISSIVEFRESNEL) {
  38996. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  38997. }
  38998. if (defines.FRESNEL) {
  38999. fallbacks.addFallback(4, "FRESNEL");
  39000. }
  39001. //Attributes
  39002. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39003. if (defines.NORMAL) {
  39004. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39005. }
  39006. if (defines.UV1) {
  39007. attribs.push(BABYLON.VertexBuffer.UVKind);
  39008. }
  39009. if (defines.UV2) {
  39010. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39011. }
  39012. if (defines.VERTEXCOLOR) {
  39013. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39014. }
  39015. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39016. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39017. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39018. var shaderName = "default";
  39019. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39020. "vFogInfos", "vFogColor", "pointSize",
  39021. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39022. "mBones",
  39023. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39024. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39025. "vReflectionPosition", "vReflectionSize",
  39026. "logarithmicDepthConstant", "vTangentSpaceParams"
  39027. ];
  39028. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39029. var uniformBuffers = ["Material", "Scene"];
  39030. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39031. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39032. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39033. uniformsNames: uniforms,
  39034. uniformBuffersNames: uniformBuffers,
  39035. samplers: samplers,
  39036. defines: defines,
  39037. maxSimultaneousLights: this._maxSimultaneousLights
  39038. });
  39039. if (this.customShaderNameResolve) {
  39040. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39041. }
  39042. var join = defines.toString();
  39043. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39044. attributes: attribs,
  39045. uniformsNames: uniforms,
  39046. uniformBuffersNames: uniformBuffers,
  39047. samplers: samplers,
  39048. defines: join,
  39049. fallbacks: fallbacks,
  39050. onCompiled: this.onCompiled,
  39051. onError: this.onError,
  39052. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39053. }, engine), defines);
  39054. this.buildUniformLayout();
  39055. }
  39056. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39057. return false;
  39058. }
  39059. defines._renderId = scene.getRenderId();
  39060. this._wasPreviouslyReady = true;
  39061. return true;
  39062. };
  39063. StandardMaterial.prototype.buildUniformLayout = function () {
  39064. // Order is important !
  39065. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39066. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39067. this._uniformBuffer.addUniform("opacityParts", 4);
  39068. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39069. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39070. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39071. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39072. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39073. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39074. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39075. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39076. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39077. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39078. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39079. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39080. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39081. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39082. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39083. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39084. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39085. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39086. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39087. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39088. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39089. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39090. this._uniformBuffer.addUniform("specularMatrix", 16);
  39091. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39092. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39093. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39094. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39095. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39096. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39097. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39098. this._uniformBuffer.addUniform("pointSize", 1);
  39099. this._uniformBuffer.create();
  39100. };
  39101. StandardMaterial.prototype.unbind = function () {
  39102. if (this._activeEffect) {
  39103. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39104. this._activeEffect.setTexture("reflection2DSampler", null);
  39105. }
  39106. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39107. this._activeEffect.setTexture("refraction2DSampler", null);
  39108. }
  39109. }
  39110. _super.prototype.unbind.call(this);
  39111. };
  39112. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39113. var scene = this.getScene();
  39114. var defines = subMesh._materialDefines;
  39115. if (!defines) {
  39116. return;
  39117. }
  39118. var effect = subMesh.effect;
  39119. if (!effect) {
  39120. return;
  39121. }
  39122. this._activeEffect = effect;
  39123. // Matrices
  39124. this.bindOnlyWorldMatrix(world);
  39125. // Normal Matrix
  39126. if (defines.OBJECTSPACE_NORMALMAP) {
  39127. world.toNormalMatrix(this._normalMatrix);
  39128. this.bindOnlyNormalMatrix(this._normalMatrix);
  39129. }
  39130. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39131. // Bones
  39132. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39133. if (mustRebind) {
  39134. this._uniformBuffer.bindToEffect(effect, "Material");
  39135. this.bindViewProjection(effect);
  39136. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39137. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39138. // Fresnel
  39139. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39140. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39141. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39142. }
  39143. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39144. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39145. }
  39146. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39147. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39148. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39149. }
  39150. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39151. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39152. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39153. }
  39154. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39155. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39156. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39157. }
  39158. }
  39159. // Textures
  39160. if (scene.texturesEnabled) {
  39161. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39162. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39163. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39164. }
  39165. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39166. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39167. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39168. }
  39169. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39170. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39171. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39172. }
  39173. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39174. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39175. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39176. if (this._reflectionTexture.boundingBoxSize) {
  39177. var cubeTexture = this._reflectionTexture;
  39178. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39179. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39180. }
  39181. }
  39182. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39183. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39184. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39185. }
  39186. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39187. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39188. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39189. }
  39190. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39191. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39192. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39193. }
  39194. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39195. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39196. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39197. if (scene._mirroredCameraPosition) {
  39198. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39199. }
  39200. else {
  39201. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39202. }
  39203. }
  39204. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39205. var depth = 1.0;
  39206. if (!this._refractionTexture.isCube) {
  39207. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39208. if (this._refractionTexture.depth) {
  39209. depth = this._refractionTexture.depth;
  39210. }
  39211. }
  39212. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39213. }
  39214. }
  39215. // Point size
  39216. if (this.pointsCloud) {
  39217. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39218. }
  39219. if (defines.SPECULARTERM) {
  39220. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39221. }
  39222. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39223. // Diffuse
  39224. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39225. }
  39226. // Textures
  39227. if (scene.texturesEnabled) {
  39228. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39229. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39230. }
  39231. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39232. effect.setTexture("ambientSampler", this._ambientTexture);
  39233. }
  39234. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39235. effect.setTexture("opacitySampler", this._opacityTexture);
  39236. }
  39237. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39238. if (this._reflectionTexture.isCube) {
  39239. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39240. }
  39241. else {
  39242. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39243. }
  39244. }
  39245. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39246. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39247. }
  39248. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39249. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39250. }
  39251. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39252. effect.setTexture("specularSampler", this._specularTexture);
  39253. }
  39254. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39255. effect.setTexture("bumpSampler", this._bumpTexture);
  39256. }
  39257. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39258. var depth = 1.0;
  39259. if (this._refractionTexture.isCube) {
  39260. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39261. }
  39262. else {
  39263. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39264. }
  39265. }
  39266. }
  39267. // Clip plane
  39268. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39269. // Colors
  39270. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39271. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39272. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39273. }
  39274. if (mustRebind || !this.isFrozen) {
  39275. // Lights
  39276. if (scene.lightsEnabled && !this._disableLighting) {
  39277. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39278. }
  39279. // View
  39280. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39281. this.bindView(effect);
  39282. }
  39283. // Fog
  39284. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39285. // Morph targets
  39286. if (defines.NUM_MORPH_INFLUENCERS) {
  39287. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39288. }
  39289. // Log. depth
  39290. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39291. // image processing
  39292. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39293. this._imageProcessingConfiguration.bind(this._activeEffect);
  39294. }
  39295. }
  39296. this._uniformBuffer.update();
  39297. this._afterBind(mesh, this._activeEffect);
  39298. };
  39299. StandardMaterial.prototype.getAnimatables = function () {
  39300. var results = [];
  39301. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39302. results.push(this._diffuseTexture);
  39303. }
  39304. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39305. results.push(this._ambientTexture);
  39306. }
  39307. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39308. results.push(this._opacityTexture);
  39309. }
  39310. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39311. results.push(this._reflectionTexture);
  39312. }
  39313. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39314. results.push(this._emissiveTexture);
  39315. }
  39316. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39317. results.push(this._specularTexture);
  39318. }
  39319. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39320. results.push(this._bumpTexture);
  39321. }
  39322. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39323. results.push(this._lightmapTexture);
  39324. }
  39325. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39326. results.push(this._refractionTexture);
  39327. }
  39328. return results;
  39329. };
  39330. StandardMaterial.prototype.getActiveTextures = function () {
  39331. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39332. if (this._diffuseTexture) {
  39333. activeTextures.push(this._diffuseTexture);
  39334. }
  39335. if (this._ambientTexture) {
  39336. activeTextures.push(this._ambientTexture);
  39337. }
  39338. if (this._opacityTexture) {
  39339. activeTextures.push(this._opacityTexture);
  39340. }
  39341. if (this._reflectionTexture) {
  39342. activeTextures.push(this._reflectionTexture);
  39343. }
  39344. if (this._emissiveTexture) {
  39345. activeTextures.push(this._emissiveTexture);
  39346. }
  39347. if (this._specularTexture) {
  39348. activeTextures.push(this._specularTexture);
  39349. }
  39350. if (this._bumpTexture) {
  39351. activeTextures.push(this._bumpTexture);
  39352. }
  39353. if (this._lightmapTexture) {
  39354. activeTextures.push(this._lightmapTexture);
  39355. }
  39356. if (this._refractionTexture) {
  39357. activeTextures.push(this._refractionTexture);
  39358. }
  39359. return activeTextures;
  39360. };
  39361. StandardMaterial.prototype.hasTexture = function (texture) {
  39362. if (_super.prototype.hasTexture.call(this, texture)) {
  39363. return true;
  39364. }
  39365. if (this._diffuseTexture === texture) {
  39366. return true;
  39367. }
  39368. if (this._ambientTexture === texture) {
  39369. return true;
  39370. }
  39371. if (this._opacityTexture === texture) {
  39372. return true;
  39373. }
  39374. if (this._reflectionTexture === texture) {
  39375. return true;
  39376. }
  39377. if (this._emissiveTexture === texture) {
  39378. return true;
  39379. }
  39380. if (this._specularTexture === texture) {
  39381. return true;
  39382. }
  39383. if (this._bumpTexture === texture) {
  39384. return true;
  39385. }
  39386. if (this._lightmapTexture === texture) {
  39387. return true;
  39388. }
  39389. if (this._refractionTexture === texture) {
  39390. return true;
  39391. }
  39392. return false;
  39393. };
  39394. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39395. if (forceDisposeTextures) {
  39396. if (this._diffuseTexture) {
  39397. this._diffuseTexture.dispose();
  39398. }
  39399. if (this._ambientTexture) {
  39400. this._ambientTexture.dispose();
  39401. }
  39402. if (this._opacityTexture) {
  39403. this._opacityTexture.dispose();
  39404. }
  39405. if (this._reflectionTexture) {
  39406. this._reflectionTexture.dispose();
  39407. }
  39408. if (this._emissiveTexture) {
  39409. this._emissiveTexture.dispose();
  39410. }
  39411. if (this._specularTexture) {
  39412. this._specularTexture.dispose();
  39413. }
  39414. if (this._bumpTexture) {
  39415. this._bumpTexture.dispose();
  39416. }
  39417. if (this._lightmapTexture) {
  39418. this._lightmapTexture.dispose();
  39419. }
  39420. if (this._refractionTexture) {
  39421. this._refractionTexture.dispose();
  39422. }
  39423. }
  39424. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39425. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39426. }
  39427. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39428. };
  39429. StandardMaterial.prototype.clone = function (name) {
  39430. var _this = this;
  39431. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39432. result.name = name;
  39433. result.id = name;
  39434. return result;
  39435. };
  39436. StandardMaterial.prototype.serialize = function () {
  39437. return BABYLON.SerializationHelper.Serialize(this);
  39438. };
  39439. // Statics
  39440. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39441. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39442. };
  39443. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39444. get: function () {
  39445. return StandardMaterial._DiffuseTextureEnabled;
  39446. },
  39447. set: function (value) {
  39448. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39449. return;
  39450. }
  39451. StandardMaterial._DiffuseTextureEnabled = value;
  39452. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39453. },
  39454. enumerable: true,
  39455. configurable: true
  39456. });
  39457. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39458. get: function () {
  39459. return StandardMaterial._AmbientTextureEnabled;
  39460. },
  39461. set: function (value) {
  39462. if (StandardMaterial._AmbientTextureEnabled === value) {
  39463. return;
  39464. }
  39465. StandardMaterial._AmbientTextureEnabled = value;
  39466. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39467. },
  39468. enumerable: true,
  39469. configurable: true
  39470. });
  39471. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39472. get: function () {
  39473. return StandardMaterial._OpacityTextureEnabled;
  39474. },
  39475. set: function (value) {
  39476. if (StandardMaterial._OpacityTextureEnabled === value) {
  39477. return;
  39478. }
  39479. StandardMaterial._OpacityTextureEnabled = value;
  39480. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39481. },
  39482. enumerable: true,
  39483. configurable: true
  39484. });
  39485. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39486. get: function () {
  39487. return StandardMaterial._ReflectionTextureEnabled;
  39488. },
  39489. set: function (value) {
  39490. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39491. return;
  39492. }
  39493. StandardMaterial._ReflectionTextureEnabled = value;
  39494. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39495. },
  39496. enumerable: true,
  39497. configurable: true
  39498. });
  39499. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39500. get: function () {
  39501. return StandardMaterial._EmissiveTextureEnabled;
  39502. },
  39503. set: function (value) {
  39504. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39505. return;
  39506. }
  39507. StandardMaterial._EmissiveTextureEnabled = value;
  39508. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39509. },
  39510. enumerable: true,
  39511. configurable: true
  39512. });
  39513. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39514. get: function () {
  39515. return StandardMaterial._SpecularTextureEnabled;
  39516. },
  39517. set: function (value) {
  39518. if (StandardMaterial._SpecularTextureEnabled === value) {
  39519. return;
  39520. }
  39521. StandardMaterial._SpecularTextureEnabled = value;
  39522. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39523. },
  39524. enumerable: true,
  39525. configurable: true
  39526. });
  39527. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39528. get: function () {
  39529. return StandardMaterial._BumpTextureEnabled;
  39530. },
  39531. set: function (value) {
  39532. if (StandardMaterial._BumpTextureEnabled === value) {
  39533. return;
  39534. }
  39535. StandardMaterial._BumpTextureEnabled = value;
  39536. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39537. },
  39538. enumerable: true,
  39539. configurable: true
  39540. });
  39541. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39542. get: function () {
  39543. return StandardMaterial._LightmapTextureEnabled;
  39544. },
  39545. set: function (value) {
  39546. if (StandardMaterial._LightmapTextureEnabled === value) {
  39547. return;
  39548. }
  39549. StandardMaterial._LightmapTextureEnabled = value;
  39550. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39551. },
  39552. enumerable: true,
  39553. configurable: true
  39554. });
  39555. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39556. get: function () {
  39557. return StandardMaterial._RefractionTextureEnabled;
  39558. },
  39559. set: function (value) {
  39560. if (StandardMaterial._RefractionTextureEnabled === value) {
  39561. return;
  39562. }
  39563. StandardMaterial._RefractionTextureEnabled = value;
  39564. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39565. },
  39566. enumerable: true,
  39567. configurable: true
  39568. });
  39569. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39570. get: function () {
  39571. return StandardMaterial._ColorGradingTextureEnabled;
  39572. },
  39573. set: function (value) {
  39574. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39575. return;
  39576. }
  39577. StandardMaterial._ColorGradingTextureEnabled = value;
  39578. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39579. },
  39580. enumerable: true,
  39581. configurable: true
  39582. });
  39583. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39584. get: function () {
  39585. return StandardMaterial._FresnelEnabled;
  39586. },
  39587. set: function (value) {
  39588. if (StandardMaterial._FresnelEnabled === value) {
  39589. return;
  39590. }
  39591. StandardMaterial._FresnelEnabled = value;
  39592. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39593. },
  39594. enumerable: true,
  39595. configurable: true
  39596. });
  39597. // Flags used to enable or disable a type of texture for all Standard Materials
  39598. StandardMaterial._DiffuseTextureEnabled = true;
  39599. StandardMaterial._AmbientTextureEnabled = true;
  39600. StandardMaterial._OpacityTextureEnabled = true;
  39601. StandardMaterial._ReflectionTextureEnabled = true;
  39602. StandardMaterial._EmissiveTextureEnabled = true;
  39603. StandardMaterial._SpecularTextureEnabled = true;
  39604. StandardMaterial._BumpTextureEnabled = true;
  39605. StandardMaterial._LightmapTextureEnabled = true;
  39606. StandardMaterial._RefractionTextureEnabled = true;
  39607. StandardMaterial._ColorGradingTextureEnabled = true;
  39608. StandardMaterial._FresnelEnabled = true;
  39609. __decorate([
  39610. BABYLON.serializeAsTexture("diffuseTexture")
  39611. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39612. __decorate([
  39613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39614. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39615. __decorate([
  39616. BABYLON.serializeAsTexture("ambientTexture")
  39617. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39618. __decorate([
  39619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39620. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39621. __decorate([
  39622. BABYLON.serializeAsTexture("opacityTexture")
  39623. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39624. __decorate([
  39625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39626. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39627. __decorate([
  39628. BABYLON.serializeAsTexture("reflectionTexture")
  39629. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39630. __decorate([
  39631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39632. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39633. __decorate([
  39634. BABYLON.serializeAsTexture("emissiveTexture")
  39635. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39636. __decorate([
  39637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39638. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39639. __decorate([
  39640. BABYLON.serializeAsTexture("specularTexture")
  39641. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39642. __decorate([
  39643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39644. ], StandardMaterial.prototype, "specularTexture", void 0);
  39645. __decorate([
  39646. BABYLON.serializeAsTexture("bumpTexture")
  39647. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39648. __decorate([
  39649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39650. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39651. __decorate([
  39652. BABYLON.serializeAsTexture("lightmapTexture")
  39653. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39654. __decorate([
  39655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39656. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39657. __decorate([
  39658. BABYLON.serializeAsTexture("refractionTexture")
  39659. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39660. __decorate([
  39661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39662. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39663. __decorate([
  39664. BABYLON.serializeAsColor3("ambient")
  39665. ], StandardMaterial.prototype, "ambientColor", void 0);
  39666. __decorate([
  39667. BABYLON.serializeAsColor3("diffuse")
  39668. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39669. __decorate([
  39670. BABYLON.serializeAsColor3("specular")
  39671. ], StandardMaterial.prototype, "specularColor", void 0);
  39672. __decorate([
  39673. BABYLON.serializeAsColor3("emissive")
  39674. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39675. __decorate([
  39676. BABYLON.serialize()
  39677. ], StandardMaterial.prototype, "specularPower", void 0);
  39678. __decorate([
  39679. BABYLON.serialize("useAlphaFromDiffuseTexture")
  39680. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  39681. __decorate([
  39682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39683. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  39684. __decorate([
  39685. BABYLON.serialize("useEmissiveAsIllumination")
  39686. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  39687. __decorate([
  39688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39689. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39690. __decorate([
  39691. BABYLON.serialize("linkEmissiveWithDiffuse")
  39692. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  39693. __decorate([
  39694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39695. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  39696. __decorate([
  39697. BABYLON.serialize("useSpecularOverAlpha")
  39698. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  39699. __decorate([
  39700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39701. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  39702. __decorate([
  39703. BABYLON.serialize("useReflectionOverAlpha")
  39704. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  39705. __decorate([
  39706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39707. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  39708. __decorate([
  39709. BABYLON.serialize("disableLighting")
  39710. ], StandardMaterial.prototype, "_disableLighting", void 0);
  39711. __decorate([
  39712. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39713. ], StandardMaterial.prototype, "disableLighting", void 0);
  39714. __decorate([
  39715. BABYLON.serialize("useObjectSpaceNormalMap")
  39716. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  39717. __decorate([
  39718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39719. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  39720. __decorate([
  39721. BABYLON.serialize("useParallax")
  39722. ], StandardMaterial.prototype, "_useParallax", void 0);
  39723. __decorate([
  39724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39725. ], StandardMaterial.prototype, "useParallax", void 0);
  39726. __decorate([
  39727. BABYLON.serialize("useParallaxOcclusion")
  39728. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  39729. __decorate([
  39730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39731. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  39732. __decorate([
  39733. BABYLON.serialize()
  39734. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  39735. __decorate([
  39736. BABYLON.serialize("roughness")
  39737. ], StandardMaterial.prototype, "_roughness", void 0);
  39738. __decorate([
  39739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39740. ], StandardMaterial.prototype, "roughness", void 0);
  39741. __decorate([
  39742. BABYLON.serialize()
  39743. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  39744. __decorate([
  39745. BABYLON.serialize()
  39746. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  39747. __decorate([
  39748. BABYLON.serialize("useLightmapAsShadowmap")
  39749. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  39750. __decorate([
  39751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39752. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39753. __decorate([
  39754. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  39755. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  39756. __decorate([
  39757. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39758. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  39759. __decorate([
  39760. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  39761. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  39762. __decorate([
  39763. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  39764. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  39765. __decorate([
  39766. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  39767. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  39768. __decorate([
  39769. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39770. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  39771. __decorate([
  39772. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  39773. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  39774. __decorate([
  39775. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39776. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  39777. __decorate([
  39778. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  39779. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  39780. __decorate([
  39781. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39782. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  39783. __decorate([
  39784. BABYLON.serialize("useReflectionFresnelFromSpecular")
  39785. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  39786. __decorate([
  39787. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39788. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  39789. __decorate([
  39790. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  39791. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  39792. __decorate([
  39793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39794. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  39795. __decorate([
  39796. BABYLON.serialize("maxSimultaneousLights")
  39797. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  39798. __decorate([
  39799. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39800. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  39801. __decorate([
  39802. BABYLON.serialize("invertNormalMapX")
  39803. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  39804. __decorate([
  39805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39806. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  39807. __decorate([
  39808. BABYLON.serialize("invertNormalMapY")
  39809. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  39810. __decorate([
  39811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39812. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  39813. __decorate([
  39814. BABYLON.serialize("twoSidedLighting")
  39815. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  39816. __decorate([
  39817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39818. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  39819. __decorate([
  39820. BABYLON.serialize()
  39821. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  39822. return StandardMaterial;
  39823. }(BABYLON.PushMaterial));
  39824. BABYLON.StandardMaterial = StandardMaterial;
  39825. })(BABYLON || (BABYLON = {}));
  39826. //# sourceMappingURL=babylon.standardMaterial.js.map
  39827. var BABYLON;
  39828. (function (BABYLON) {
  39829. /**
  39830. * Manages the defines for the PBR Material.
  39831. */
  39832. var PBRMaterialDefines = /** @class */ (function (_super) {
  39833. __extends(PBRMaterialDefines, _super);
  39834. /**
  39835. * Initializes the PBR Material defines.
  39836. */
  39837. function PBRMaterialDefines() {
  39838. var _this = _super.call(this) || this;
  39839. _this.PBR = true;
  39840. _this.MAINUV1 = false;
  39841. _this.MAINUV2 = false;
  39842. _this.UV1 = false;
  39843. _this.UV2 = false;
  39844. _this.ALBEDO = false;
  39845. _this.ALBEDODIRECTUV = 0;
  39846. _this.VERTEXCOLOR = false;
  39847. _this.AMBIENT = false;
  39848. _this.AMBIENTDIRECTUV = 0;
  39849. _this.AMBIENTINGRAYSCALE = false;
  39850. _this.OPACITY = false;
  39851. _this.VERTEXALPHA = false;
  39852. _this.OPACITYDIRECTUV = 0;
  39853. _this.OPACITYRGB = false;
  39854. _this.ALPHATEST = false;
  39855. _this.DEPTHPREPASS = false;
  39856. _this.ALPHABLEND = false;
  39857. _this.ALPHAFROMALBEDO = false;
  39858. _this.ALPHATESTVALUE = 0.5;
  39859. _this.SPECULAROVERALPHA = false;
  39860. _this.RADIANCEOVERALPHA = false;
  39861. _this.ALPHAFRESNEL = false;
  39862. _this.LINEARALPHAFRESNEL = false;
  39863. _this.PREMULTIPLYALPHA = false;
  39864. _this.EMISSIVE = false;
  39865. _this.EMISSIVEDIRECTUV = 0;
  39866. _this.REFLECTIVITY = false;
  39867. _this.REFLECTIVITYDIRECTUV = 0;
  39868. _this.SPECULARTERM = false;
  39869. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  39870. _this.MICROSURFACEAUTOMATIC = false;
  39871. _this.LODBASEDMICROSFURACE = false;
  39872. _this.MICROSURFACEMAP = false;
  39873. _this.MICROSURFACEMAPDIRECTUV = 0;
  39874. _this.METALLICWORKFLOW = false;
  39875. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  39876. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  39877. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  39878. _this.AOSTOREINMETALMAPRED = false;
  39879. _this.ENVIRONMENTBRDF = false;
  39880. _this.NORMAL = false;
  39881. _this.TANGENT = false;
  39882. _this.BUMP = false;
  39883. _this.BUMPDIRECTUV = 0;
  39884. _this.OBJECTSPACE_NORMALMAP = false;
  39885. _this.PARALLAX = false;
  39886. _this.PARALLAXOCCLUSION = false;
  39887. _this.NORMALXYSCALE = true;
  39888. _this.LIGHTMAP = false;
  39889. _this.LIGHTMAPDIRECTUV = 0;
  39890. _this.USELIGHTMAPASSHADOWMAP = false;
  39891. _this.REFLECTION = false;
  39892. _this.REFLECTIONMAP_3D = false;
  39893. _this.REFLECTIONMAP_SPHERICAL = false;
  39894. _this.REFLECTIONMAP_PLANAR = false;
  39895. _this.REFLECTIONMAP_CUBIC = false;
  39896. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39897. _this.REFLECTIONMAP_PROJECTION = false;
  39898. _this.REFLECTIONMAP_SKYBOX = false;
  39899. _this.REFLECTIONMAP_EXPLICIT = false;
  39900. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39901. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39902. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39903. _this.INVERTCUBICMAP = false;
  39904. _this.USESPHERICALFROMREFLECTIONMAP = false;
  39905. _this.USESPHERICALINVERTEX = false;
  39906. _this.REFLECTIONMAP_OPPOSITEZ = false;
  39907. _this.LODINREFLECTIONALPHA = false;
  39908. _this.GAMMAREFLECTION = false;
  39909. _this.RADIANCEOCCLUSION = false;
  39910. _this.HORIZONOCCLUSION = false;
  39911. _this.REFRACTION = false;
  39912. _this.REFRACTIONMAP_3D = false;
  39913. _this.REFRACTIONMAP_OPPOSITEZ = false;
  39914. _this.LODINREFRACTIONALPHA = false;
  39915. _this.GAMMAREFRACTION = false;
  39916. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  39917. _this.INSTANCES = false;
  39918. _this.NUM_BONE_INFLUENCERS = 0;
  39919. _this.BonesPerMesh = 0;
  39920. _this.NONUNIFORMSCALING = false;
  39921. _this.MORPHTARGETS = false;
  39922. _this.MORPHTARGETS_NORMAL = false;
  39923. _this.MORPHTARGETS_TANGENT = false;
  39924. _this.NUM_MORPH_INFLUENCERS = 0;
  39925. _this.IMAGEPROCESSING = false;
  39926. _this.VIGNETTE = false;
  39927. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39928. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39929. _this.TONEMAPPING = false;
  39930. _this.CONTRAST = false;
  39931. _this.COLORCURVES = false;
  39932. _this.COLORGRADING = false;
  39933. _this.COLORGRADING3D = false;
  39934. _this.SAMPLER3DGREENDEPTH = false;
  39935. _this.SAMPLER3DBGRMAP = false;
  39936. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39937. _this.EXPOSURE = false;
  39938. _this.USEPHYSICALLIGHTFALLOFF = false;
  39939. _this.TWOSIDEDLIGHTING = false;
  39940. _this.SHADOWFLOAT = false;
  39941. _this.CLIPPLANE = false;
  39942. _this.POINTSIZE = false;
  39943. _this.FOG = false;
  39944. _this.LOGARITHMICDEPTH = false;
  39945. _this.FORCENORMALFORWARD = false;
  39946. _this.rebuild();
  39947. return _this;
  39948. }
  39949. /**
  39950. * Resets the PBR Material defines.
  39951. */
  39952. PBRMaterialDefines.prototype.reset = function () {
  39953. _super.prototype.reset.call(this);
  39954. this.ALPHATESTVALUE = 0.5;
  39955. this.PBR = true;
  39956. };
  39957. return PBRMaterialDefines;
  39958. }(BABYLON.MaterialDefines));
  39959. /**
  39960. * The Physically based material base class of BJS.
  39961. *
  39962. * This offers the main features of a standard PBR material.
  39963. * For more information, please refer to the documentation :
  39964. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39965. */
  39966. var PBRBaseMaterial = /** @class */ (function (_super) {
  39967. __extends(PBRBaseMaterial, _super);
  39968. /**
  39969. * Instantiates a new PBRMaterial instance.
  39970. *
  39971. * @param name The material name
  39972. * @param scene The scene the material will be use in.
  39973. */
  39974. function PBRBaseMaterial(name, scene) {
  39975. var _this = _super.call(this, name, scene) || this;
  39976. /**
  39977. * Intensity of the direct lights e.g. the four lights available in your scene.
  39978. * This impacts both the direct diffuse and specular highlights.
  39979. */
  39980. _this._directIntensity = 1.0;
  39981. /**
  39982. * Intensity of the emissive part of the material.
  39983. * This helps controlling the emissive effect without modifying the emissive color.
  39984. */
  39985. _this._emissiveIntensity = 1.0;
  39986. /**
  39987. * Intensity of the environment e.g. how much the environment will light the object
  39988. * either through harmonics for rough material or through the refelction for shiny ones.
  39989. */
  39990. _this._environmentIntensity = 1.0;
  39991. /**
  39992. * This is a special control allowing the reduction of the specular highlights coming from the
  39993. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39994. */
  39995. _this._specularIntensity = 1.0;
  39996. /**
  39997. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  39998. */
  39999. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40000. /**
  40001. * Debug Control allowing disabling the bump map on this material.
  40002. */
  40003. _this._disableBumpMap = false;
  40004. /**
  40005. * AKA Occlusion Texture Intensity in other nomenclature.
  40006. */
  40007. _this._ambientTextureStrength = 1.0;
  40008. /**
  40009. * The color of a material in ambient lighting.
  40010. */
  40011. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40012. /**
  40013. * AKA Diffuse Color in other nomenclature.
  40014. */
  40015. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40016. /**
  40017. * AKA Specular Color in other nomenclature.
  40018. */
  40019. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40020. /**
  40021. * The color applied when light is reflected from a material.
  40022. */
  40023. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40024. /**
  40025. * The color applied when light is emitted from a material.
  40026. */
  40027. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40028. /**
  40029. * AKA Glossiness in other nomenclature.
  40030. */
  40031. _this._microSurface = 0.9;
  40032. /**
  40033. * source material index of refraction (IOR)' / 'destination material IOR.
  40034. */
  40035. _this._indexOfRefraction = 0.66;
  40036. /**
  40037. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40038. */
  40039. _this._invertRefractionY = false;
  40040. /**
  40041. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40042. * Materials half opaque for instance using refraction could benefit from this control.
  40043. */
  40044. _this._linkRefractionWithTransparency = false;
  40045. /**
  40046. * Specifies that the material will use the light map as a show map.
  40047. */
  40048. _this._useLightmapAsShadowmap = false;
  40049. /**
  40050. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40051. * makes the reflect vector face the model (under horizon).
  40052. */
  40053. _this._useHorizonOcclusion = true;
  40054. /**
  40055. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40056. * too much the area relying on ambient texture to define their ambient occlusion.
  40057. */
  40058. _this._useRadianceOcclusion = true;
  40059. /**
  40060. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40061. */
  40062. _this._useAlphaFromAlbedoTexture = false;
  40063. /**
  40064. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40065. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40066. */
  40067. _this._useSpecularOverAlpha = true;
  40068. /**
  40069. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40070. */
  40071. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40072. /**
  40073. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40074. */
  40075. _this._useRoughnessFromMetallicTextureAlpha = true;
  40076. /**
  40077. * Specifies if the metallic texture contains the roughness information in its green channel.
  40078. */
  40079. _this._useRoughnessFromMetallicTextureGreen = false;
  40080. /**
  40081. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40082. */
  40083. _this._useMetallnessFromMetallicTextureBlue = false;
  40084. /**
  40085. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40086. */
  40087. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40088. /**
  40089. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40090. */
  40091. _this._useAmbientInGrayScale = false;
  40092. /**
  40093. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40094. * The material will try to infer what glossiness each pixel should be.
  40095. */
  40096. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40097. /**
  40098. * BJS is using an harcoded light falloff based on a manually sets up range.
  40099. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40100. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40101. */
  40102. _this._usePhysicalLightFalloff = true;
  40103. /**
  40104. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40105. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40106. */
  40107. _this._useRadianceOverAlpha = true;
  40108. /**
  40109. * Allows using an object space normal map (instead of tangent space).
  40110. */
  40111. _this._useObjectSpaceNormalMap = false;
  40112. /**
  40113. * Allows using the bump map in parallax mode.
  40114. */
  40115. _this._useParallax = false;
  40116. /**
  40117. * Allows using the bump map in parallax occlusion mode.
  40118. */
  40119. _this._useParallaxOcclusion = false;
  40120. /**
  40121. * Controls the scale bias of the parallax mode.
  40122. */
  40123. _this._parallaxScaleBias = 0.05;
  40124. /**
  40125. * If sets to true, disables all the lights affecting the material.
  40126. */
  40127. _this._disableLighting = false;
  40128. /**
  40129. * Number of Simultaneous lights allowed on the material.
  40130. */
  40131. _this._maxSimultaneousLights = 4;
  40132. /**
  40133. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40134. */
  40135. _this._invertNormalMapX = false;
  40136. /**
  40137. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40138. */
  40139. _this._invertNormalMapY = false;
  40140. /**
  40141. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40142. */
  40143. _this._twoSidedLighting = false;
  40144. /**
  40145. * Defines the alpha limits in alpha test mode.
  40146. */
  40147. _this._alphaCutOff = 0.4;
  40148. /**
  40149. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40150. */
  40151. _this._forceAlphaTest = false;
  40152. /**
  40153. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40154. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40155. */
  40156. _this._useAlphaFresnel = false;
  40157. /**
  40158. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40159. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40160. */
  40161. _this._useLinearAlphaFresnel = false;
  40162. /**
  40163. * The transparency mode of the material.
  40164. */
  40165. _this._transparencyMode = null;
  40166. /**
  40167. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40168. * from cos thetav and roughness:
  40169. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40170. */
  40171. _this._environmentBRDFTexture = null;
  40172. /**
  40173. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40174. */
  40175. _this._forceIrradianceInFragment = false;
  40176. /**
  40177. * Force normal to face away from face.
  40178. */
  40179. _this._forceNormalForward = false;
  40180. /**
  40181. * Force metallic workflow.
  40182. */
  40183. _this._forceMetallicWorkflow = false;
  40184. /**
  40185. * Stores the available render targets.
  40186. */
  40187. _this._renderTargets = new BABYLON.SmartArray(16);
  40188. /**
  40189. * Sets the global ambient color for the material used in lighting calculations.
  40190. */
  40191. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40192. // Setup the default processing configuration to the scene.
  40193. _this._attachImageProcessingConfiguration(null);
  40194. _this.getRenderTargetTextures = function () {
  40195. _this._renderTargets.reset();
  40196. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40197. _this._renderTargets.push(_this._reflectionTexture);
  40198. }
  40199. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40200. _this._renderTargets.push(_this._refractionTexture);
  40201. }
  40202. return _this._renderTargets;
  40203. };
  40204. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40205. return _this;
  40206. }
  40207. /**
  40208. * Attaches a new image processing configuration to the PBR Material.
  40209. * @param configuration
  40210. */
  40211. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40212. var _this = this;
  40213. if (configuration === this._imageProcessingConfiguration) {
  40214. return;
  40215. }
  40216. // Detaches observer.
  40217. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40218. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40219. }
  40220. // Pick the scene configuration if needed.
  40221. if (!configuration) {
  40222. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40223. }
  40224. else {
  40225. this._imageProcessingConfiguration = configuration;
  40226. }
  40227. // Attaches observer.
  40228. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40229. _this._markAllSubMeshesAsImageProcessingDirty();
  40230. });
  40231. };
  40232. /**
  40233. * Gets the name of the material class.
  40234. */
  40235. PBRBaseMaterial.prototype.getClassName = function () {
  40236. return "PBRBaseMaterial";
  40237. };
  40238. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40239. /**
  40240. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40241. */
  40242. get: function () {
  40243. return this._useLogarithmicDepth;
  40244. },
  40245. /**
  40246. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40247. */
  40248. set: function (value) {
  40249. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40250. },
  40251. enumerable: true,
  40252. configurable: true
  40253. });
  40254. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40255. /**
  40256. * Gets the current transparency mode.
  40257. */
  40258. get: function () {
  40259. return this._transparencyMode;
  40260. },
  40261. /**
  40262. * Sets the transparency mode of the material.
  40263. */
  40264. set: function (value) {
  40265. if (this._transparencyMode === value) {
  40266. return;
  40267. }
  40268. this._transparencyMode = value;
  40269. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40270. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40271. },
  40272. enumerable: true,
  40273. configurable: true
  40274. });
  40275. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40276. /**
  40277. * Returns true if alpha blending should be disabled.
  40278. */
  40279. get: function () {
  40280. return (this._linkRefractionWithTransparency ||
  40281. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40282. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40283. },
  40284. enumerable: true,
  40285. configurable: true
  40286. });
  40287. /**
  40288. * Specifies whether or not this material should be rendered in alpha blend mode.
  40289. */
  40290. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40291. if (this._disableAlphaBlending) {
  40292. return false;
  40293. }
  40294. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40295. };
  40296. /**
  40297. * Specifies if the mesh will require alpha blending.
  40298. * @param mesh - BJS mesh.
  40299. */
  40300. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40301. if (this._disableAlphaBlending) {
  40302. return false;
  40303. }
  40304. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40305. };
  40306. /**
  40307. * Specifies whether or not this material should be rendered in alpha test mode.
  40308. */
  40309. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40310. if (this._forceAlphaTest) {
  40311. return true;
  40312. }
  40313. if (this._linkRefractionWithTransparency) {
  40314. return false;
  40315. }
  40316. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40317. };
  40318. /**
  40319. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40320. */
  40321. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40322. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40323. };
  40324. /**
  40325. * Gets the texture used for the alpha test.
  40326. */
  40327. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40328. return this._albedoTexture;
  40329. };
  40330. /**
  40331. * Specifies that the submesh is ready to be used.
  40332. * @param mesh - BJS mesh.
  40333. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40334. * @param useInstances - Specifies that instances should be used.
  40335. * @returns - boolean indicating that the submesh is ready or not.
  40336. */
  40337. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40338. if (subMesh.effect && this.isFrozen) {
  40339. if (this._wasPreviouslyReady) {
  40340. return true;
  40341. }
  40342. }
  40343. if (!subMesh._materialDefines) {
  40344. subMesh._materialDefines = new PBRMaterialDefines();
  40345. }
  40346. var defines = subMesh._materialDefines;
  40347. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40348. if (defines._renderId === this.getScene().getRenderId()) {
  40349. return true;
  40350. }
  40351. }
  40352. var scene = this.getScene();
  40353. var engine = scene.getEngine();
  40354. if (defines._areTexturesDirty) {
  40355. if (scene.texturesEnabled) {
  40356. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40357. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40358. return false;
  40359. }
  40360. }
  40361. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40362. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40363. return false;
  40364. }
  40365. }
  40366. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40367. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40368. return false;
  40369. }
  40370. }
  40371. var reflectionTexture = this._getReflectionTexture();
  40372. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40373. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40374. return false;
  40375. }
  40376. }
  40377. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40378. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40379. return false;
  40380. }
  40381. }
  40382. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40383. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40384. return false;
  40385. }
  40386. }
  40387. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40388. if (this._metallicTexture) {
  40389. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40390. return false;
  40391. }
  40392. }
  40393. else if (this._reflectivityTexture) {
  40394. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40395. return false;
  40396. }
  40397. }
  40398. if (this._microSurfaceTexture) {
  40399. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40400. return false;
  40401. }
  40402. }
  40403. }
  40404. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40405. // Bump texture cannot be not blocking.
  40406. if (!this._bumpTexture.isReady()) {
  40407. return false;
  40408. }
  40409. }
  40410. var refractionTexture = this._getRefractionTexture();
  40411. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40412. if (!refractionTexture.isReadyOrNotBlocking()) {
  40413. return false;
  40414. }
  40415. }
  40416. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40417. // This is blocking.
  40418. if (!this._environmentBRDFTexture.isReady()) {
  40419. return false;
  40420. }
  40421. }
  40422. }
  40423. }
  40424. if (defines._areImageProcessingDirty) {
  40425. if (!this._imageProcessingConfiguration.isReady()) {
  40426. return false;
  40427. }
  40428. }
  40429. if (!engine.getCaps().standardDerivatives) {
  40430. var bufferMesh = null;
  40431. if (mesh.getClassName() === "InstancedMesh") {
  40432. bufferMesh = mesh.sourceMesh;
  40433. }
  40434. else if (mesh.getClassName() === "Mesh") {
  40435. bufferMesh = mesh;
  40436. }
  40437. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40438. bufferMesh.createNormals(true);
  40439. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40440. }
  40441. }
  40442. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40443. if (effect) {
  40444. scene.resetCachedMaterial();
  40445. subMesh.setEffect(effect, defines);
  40446. this.buildUniformLayout();
  40447. }
  40448. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40449. return false;
  40450. }
  40451. defines._renderId = scene.getRenderId();
  40452. this._wasPreviouslyReady = true;
  40453. return true;
  40454. };
  40455. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40456. if (onCompiled === void 0) { onCompiled = null; }
  40457. if (onError === void 0) { onError = null; }
  40458. if (useInstances === void 0) { useInstances = null; }
  40459. if (useClipPlane === void 0) { useClipPlane = null; }
  40460. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40461. if (!defines.isDirty) {
  40462. return null;
  40463. }
  40464. defines.markAsProcessed();
  40465. var scene = this.getScene();
  40466. var engine = scene.getEngine();
  40467. // Fallbacks
  40468. var fallbacks = new BABYLON.EffectFallbacks();
  40469. var fallbackRank = 0;
  40470. if (defines.USESPHERICALINVERTEX) {
  40471. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40472. }
  40473. if (defines.FOG) {
  40474. fallbacks.addFallback(fallbackRank, "FOG");
  40475. }
  40476. if (defines.POINTSIZE) {
  40477. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40478. }
  40479. if (defines.LOGARITHMICDEPTH) {
  40480. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40481. }
  40482. if (defines.PARALLAX) {
  40483. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40484. }
  40485. if (defines.PARALLAXOCCLUSION) {
  40486. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40487. }
  40488. if (defines.ENVIRONMENTBRDF) {
  40489. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40490. }
  40491. if (defines.TANGENT) {
  40492. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40493. }
  40494. if (defines.BUMP) {
  40495. fallbacks.addFallback(fallbackRank++, "BUMP");
  40496. }
  40497. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40498. if (defines.SPECULARTERM) {
  40499. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40500. }
  40501. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40502. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40503. }
  40504. if (defines.LIGHTMAP) {
  40505. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40506. }
  40507. if (defines.NORMAL) {
  40508. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40509. }
  40510. if (defines.AMBIENT) {
  40511. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40512. }
  40513. if (defines.EMISSIVE) {
  40514. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40515. }
  40516. if (defines.VERTEXCOLOR) {
  40517. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40518. }
  40519. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40520. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40521. }
  40522. if (defines.MORPHTARGETS) {
  40523. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40524. }
  40525. //Attributes
  40526. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40527. if (defines.NORMAL) {
  40528. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40529. }
  40530. if (defines.TANGENT) {
  40531. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40532. }
  40533. if (defines.UV1) {
  40534. attribs.push(BABYLON.VertexBuffer.UVKind);
  40535. }
  40536. if (defines.UV2) {
  40537. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40538. }
  40539. if (defines.VERTEXCOLOR) {
  40540. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40541. }
  40542. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40543. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40544. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40545. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40546. "vFogInfos", "vFogColor", "pointSize",
  40547. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40548. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40549. "mBones",
  40550. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40551. "vLightingIntensity",
  40552. "logarithmicDepthConstant",
  40553. "vSphericalX", "vSphericalY", "vSphericalZ",
  40554. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40555. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40556. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40557. "vTangentSpaceParams"
  40558. ];
  40559. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40560. "bumpSampler", "lightmapSampler", "opacitySampler",
  40561. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40562. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40563. "microSurfaceSampler", "environmentBrdfSampler"];
  40564. var uniformBuffers = ["Material", "Scene"];
  40565. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40566. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40567. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40568. uniformsNames: uniforms,
  40569. uniformBuffersNames: uniformBuffers,
  40570. samplers: samplers,
  40571. defines: defines,
  40572. maxSimultaneousLights: this._maxSimultaneousLights
  40573. });
  40574. var join = defines.toString();
  40575. return engine.createEffect("pbr", {
  40576. attributes: attribs,
  40577. uniformsNames: uniforms,
  40578. uniformBuffersNames: uniformBuffers,
  40579. samplers: samplers,
  40580. defines: join,
  40581. fallbacks: fallbacks,
  40582. onCompiled: onCompiled,
  40583. onError: onError,
  40584. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40585. }, engine);
  40586. };
  40587. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40588. if (useInstances === void 0) { useInstances = null; }
  40589. if (useClipPlane === void 0) { useClipPlane = null; }
  40590. var scene = this.getScene();
  40591. var engine = scene.getEngine();
  40592. // Lights
  40593. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40594. defines._needNormals = true;
  40595. // Textures
  40596. if (defines._areTexturesDirty) {
  40597. defines._needUVs = false;
  40598. if (scene.texturesEnabled) {
  40599. if (scene.getEngine().getCaps().textureLOD) {
  40600. defines.LODBASEDMICROSFURACE = true;
  40601. }
  40602. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40603. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40604. }
  40605. else {
  40606. defines.ALBEDO = false;
  40607. }
  40608. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40609. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40610. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40611. }
  40612. else {
  40613. defines.AMBIENT = false;
  40614. }
  40615. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40616. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40617. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40618. }
  40619. else {
  40620. defines.OPACITY = false;
  40621. }
  40622. var reflectionTexture = this._getReflectionTexture();
  40623. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40624. defines.REFLECTION = true;
  40625. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40626. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40627. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40628. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40629. defines.INVERTCUBICMAP = true;
  40630. }
  40631. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40632. switch (reflectionTexture.coordinatesMode) {
  40633. case BABYLON.Texture.CUBIC_MODE:
  40634. case BABYLON.Texture.INVCUBIC_MODE:
  40635. defines.REFLECTIONMAP_CUBIC = true;
  40636. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40637. break;
  40638. case BABYLON.Texture.EXPLICIT_MODE:
  40639. defines.REFLECTIONMAP_EXPLICIT = true;
  40640. break;
  40641. case BABYLON.Texture.PLANAR_MODE:
  40642. defines.REFLECTIONMAP_PLANAR = true;
  40643. break;
  40644. case BABYLON.Texture.PROJECTION_MODE:
  40645. defines.REFLECTIONMAP_PROJECTION = true;
  40646. break;
  40647. case BABYLON.Texture.SKYBOX_MODE:
  40648. defines.REFLECTIONMAP_SKYBOX = true;
  40649. break;
  40650. case BABYLON.Texture.SPHERICAL_MODE:
  40651. defines.REFLECTIONMAP_SPHERICAL = true;
  40652. break;
  40653. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40654. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40655. break;
  40656. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40657. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40658. break;
  40659. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40660. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40661. break;
  40662. }
  40663. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40664. if (reflectionTexture.sphericalPolynomial) {
  40665. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40666. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40667. defines.USESPHERICALINVERTEX = false;
  40668. }
  40669. else {
  40670. defines.USESPHERICALINVERTEX = true;
  40671. }
  40672. }
  40673. }
  40674. }
  40675. else {
  40676. defines.REFLECTION = false;
  40677. defines.REFLECTIONMAP_3D = false;
  40678. defines.REFLECTIONMAP_SPHERICAL = false;
  40679. defines.REFLECTIONMAP_PLANAR = false;
  40680. defines.REFLECTIONMAP_CUBIC = false;
  40681. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40682. defines.REFLECTIONMAP_PROJECTION = false;
  40683. defines.REFLECTIONMAP_SKYBOX = false;
  40684. defines.REFLECTIONMAP_EXPLICIT = false;
  40685. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40686. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40687. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40688. defines.INVERTCUBICMAP = false;
  40689. defines.USESPHERICALFROMREFLECTIONMAP = false;
  40690. defines.USESPHERICALINVERTEX = false;
  40691. defines.REFLECTIONMAP_OPPOSITEZ = false;
  40692. defines.LODINREFLECTIONALPHA = false;
  40693. defines.GAMMAREFLECTION = false;
  40694. }
  40695. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40696. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  40697. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40698. }
  40699. else {
  40700. defines.LIGHTMAP = false;
  40701. }
  40702. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40703. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  40704. }
  40705. else {
  40706. defines.EMISSIVE = false;
  40707. }
  40708. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40709. if (this._metallicTexture) {
  40710. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  40711. defines.METALLICWORKFLOW = true;
  40712. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  40713. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  40714. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  40715. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  40716. }
  40717. else if (this._reflectivityTexture) {
  40718. defines.METALLICWORKFLOW = false;
  40719. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  40720. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  40721. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  40722. }
  40723. else {
  40724. defines.METALLICWORKFLOW = false;
  40725. defines.REFLECTIVITY = false;
  40726. }
  40727. if (this._microSurfaceTexture) {
  40728. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  40729. }
  40730. else {
  40731. defines.MICROSURFACEMAP = false;
  40732. }
  40733. }
  40734. else {
  40735. defines.REFLECTIVITY = false;
  40736. defines.MICROSURFACEMAP = false;
  40737. }
  40738. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40739. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40740. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40741. defines.PARALLAX = true;
  40742. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  40743. }
  40744. else {
  40745. defines.PARALLAX = false;
  40746. }
  40747. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  40748. }
  40749. else {
  40750. defines.BUMP = false;
  40751. }
  40752. var refractionTexture = this._getRefractionTexture();
  40753. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40754. defines.REFRACTION = true;
  40755. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  40756. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  40757. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  40758. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  40759. if (this._linkRefractionWithTransparency) {
  40760. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  40761. }
  40762. }
  40763. else {
  40764. defines.REFRACTION = false;
  40765. }
  40766. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40767. defines.ENVIRONMENTBRDF = true;
  40768. }
  40769. else {
  40770. defines.ENVIRONMENTBRDF = false;
  40771. }
  40772. if (this._shouldUseAlphaFromAlbedoTexture()) {
  40773. defines.ALPHAFROMALBEDO = true;
  40774. }
  40775. else {
  40776. defines.ALPHAFROMALBEDO = false;
  40777. }
  40778. }
  40779. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40780. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  40781. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  40782. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  40783. defines.METALLICWORKFLOW = true;
  40784. }
  40785. else {
  40786. defines.METALLICWORKFLOW = false;
  40787. }
  40788. if (!this.backFaceCulling && this._twoSidedLighting) {
  40789. defines.TWOSIDEDLIGHTING = true;
  40790. }
  40791. else {
  40792. defines.TWOSIDEDLIGHTING = false;
  40793. }
  40794. defines.ALPHATESTVALUE = this._alphaCutOff;
  40795. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40796. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  40797. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  40798. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  40799. }
  40800. if (defines._areImageProcessingDirty) {
  40801. this._imageProcessingConfiguration.prepareDefines(defines);
  40802. }
  40803. defines.FORCENORMALFORWARD = this._forceNormalForward;
  40804. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  40805. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  40806. // Misc.
  40807. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  40808. // Values that need to be evaluated on every frame
  40809. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  40810. // Attribs
  40811. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  40812. };
  40813. /**
  40814. * Force shader compilation
  40815. */
  40816. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  40817. var _this = this;
  40818. var localOptions = __assign({ clipPlane: false }, options);
  40819. var defines = new PBRMaterialDefines();
  40820. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  40821. if (effect.isReady()) {
  40822. if (onCompiled) {
  40823. onCompiled(this);
  40824. }
  40825. }
  40826. else {
  40827. effect.onCompileObservable.add(function () {
  40828. if (onCompiled) {
  40829. onCompiled(_this);
  40830. }
  40831. });
  40832. }
  40833. };
  40834. /**
  40835. * Initializes the uniform buffer layout for the shader.
  40836. */
  40837. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  40838. // Order is important !
  40839. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  40840. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  40841. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40842. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40843. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40844. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  40845. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  40846. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40847. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40848. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40849. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40850. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40851. this._uniformBuffer.addUniform("albedoMatrix", 16);
  40852. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40853. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40854. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40855. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40856. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  40857. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  40858. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40859. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40860. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40861. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40862. this._uniformBuffer.addUniform("vReflectionColor", 3);
  40863. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  40864. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  40865. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  40866. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  40867. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  40868. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40869. this._uniformBuffer.addUniform("pointSize", 1);
  40870. this._uniformBuffer.create();
  40871. };
  40872. /**
  40873. * Unbinds the textures.
  40874. */
  40875. PBRBaseMaterial.prototype.unbind = function () {
  40876. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40877. this._uniformBuffer.setTexture("reflectionSampler", null);
  40878. }
  40879. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40880. this._uniformBuffer.setTexture("refractionSampler", null);
  40881. }
  40882. _super.prototype.unbind.call(this);
  40883. };
  40884. /**
  40885. * Binds the submesh data.
  40886. * @param world - The world matrix.
  40887. * @param mesh - The BJS mesh.
  40888. * @param subMesh - A submesh of the BJS mesh.
  40889. */
  40890. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40891. var scene = this.getScene();
  40892. var defines = subMesh._materialDefines;
  40893. if (!defines) {
  40894. return;
  40895. }
  40896. var effect = subMesh.effect;
  40897. if (!effect) {
  40898. return;
  40899. }
  40900. this._activeEffect = effect;
  40901. // Matrices
  40902. this.bindOnlyWorldMatrix(world);
  40903. // Normal Matrix
  40904. if (defines.OBJECTSPACE_NORMALMAP) {
  40905. world.toNormalMatrix(this._normalMatrix);
  40906. this.bindOnlyNormalMatrix(this._normalMatrix);
  40907. }
  40908. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40909. // Bones
  40910. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  40911. var reflectionTexture = null;
  40912. if (mustRebind) {
  40913. this._uniformBuffer.bindToEffect(effect, "Material");
  40914. this.bindViewProjection(effect);
  40915. reflectionTexture = this._getReflectionTexture();
  40916. var refractionTexture = this._getRefractionTexture();
  40917. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40918. // Texture uniforms
  40919. if (scene.texturesEnabled) {
  40920. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40921. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  40922. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  40923. }
  40924. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40925. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  40926. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40927. }
  40928. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40929. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40930. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40931. }
  40932. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40933. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  40934. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  40935. if (reflectionTexture.boundingBoxSize) {
  40936. var cubeTexture = reflectionTexture;
  40937. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40938. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40939. }
  40940. var polynomials = reflectionTexture.sphericalPolynomial;
  40941. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  40942. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  40943. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  40944. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  40945. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  40946. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  40947. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  40948. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  40949. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  40950. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  40951. }
  40952. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  40953. }
  40954. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40955. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40956. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40957. }
  40958. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40959. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40960. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40961. }
  40962. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40963. if (this._metallicTexture) {
  40964. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  40965. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  40966. }
  40967. else if (this._reflectivityTexture) {
  40968. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  40969. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  40970. }
  40971. if (this._microSurfaceTexture) {
  40972. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  40973. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  40974. }
  40975. }
  40976. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40977. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  40978. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40979. if (scene._mirroredCameraPosition) {
  40980. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40981. }
  40982. else {
  40983. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40984. }
  40985. }
  40986. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40987. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  40988. var depth = 1.0;
  40989. if (!refractionTexture.isCube) {
  40990. if (refractionTexture.depth) {
  40991. depth = refractionTexture.depth;
  40992. }
  40993. }
  40994. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  40995. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  40996. }
  40997. }
  40998. // Point size
  40999. if (this.pointsCloud) {
  41000. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41001. }
  41002. // Colors
  41003. if (defines.METALLICWORKFLOW) {
  41004. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41005. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41006. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41007. }
  41008. else {
  41009. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41010. }
  41011. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41012. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41013. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41014. // Misc
  41015. this._lightingInfos.x = this._directIntensity;
  41016. this._lightingInfos.y = this._emissiveIntensity;
  41017. this._lightingInfos.z = this._environmentIntensity;
  41018. this._lightingInfos.w = this._specularIntensity;
  41019. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41020. }
  41021. // Textures
  41022. if (scene.texturesEnabled) {
  41023. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41024. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41025. }
  41026. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41027. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41028. }
  41029. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41030. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41031. }
  41032. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41033. if (defines.LODBASEDMICROSFURACE) {
  41034. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41035. }
  41036. else {
  41037. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41038. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41039. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41040. }
  41041. }
  41042. if (defines.ENVIRONMENTBRDF) {
  41043. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41044. }
  41045. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41046. if (defines.LODBASEDMICROSFURACE) {
  41047. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41048. }
  41049. else {
  41050. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41051. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41052. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41053. }
  41054. }
  41055. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41056. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41057. }
  41058. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41059. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41060. }
  41061. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41062. if (this._metallicTexture) {
  41063. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41064. }
  41065. else if (this._reflectivityTexture) {
  41066. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41067. }
  41068. if (this._microSurfaceTexture) {
  41069. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41070. }
  41071. }
  41072. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41073. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41074. }
  41075. }
  41076. // Clip plane
  41077. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41078. // Colors
  41079. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41080. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41081. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41082. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41083. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41084. }
  41085. if (mustRebind || !this.isFrozen) {
  41086. // Lights
  41087. if (scene.lightsEnabled && !this._disableLighting) {
  41088. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41089. }
  41090. // View
  41091. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41092. this.bindView(effect);
  41093. }
  41094. // Fog
  41095. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41096. // Morph targets
  41097. if (defines.NUM_MORPH_INFLUENCERS) {
  41098. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41099. }
  41100. // image processing
  41101. this._imageProcessingConfiguration.bind(this._activeEffect);
  41102. // Log. depth
  41103. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41104. }
  41105. this._uniformBuffer.update();
  41106. this._afterBind(mesh);
  41107. };
  41108. /**
  41109. * Returns the animatable textures.
  41110. * @returns - Array of animatable textures.
  41111. */
  41112. PBRBaseMaterial.prototype.getAnimatables = function () {
  41113. var results = [];
  41114. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41115. results.push(this._albedoTexture);
  41116. }
  41117. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41118. results.push(this._ambientTexture);
  41119. }
  41120. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41121. results.push(this._opacityTexture);
  41122. }
  41123. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41124. results.push(this._reflectionTexture);
  41125. }
  41126. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41127. results.push(this._emissiveTexture);
  41128. }
  41129. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41130. results.push(this._metallicTexture);
  41131. }
  41132. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41133. results.push(this._reflectivityTexture);
  41134. }
  41135. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41136. results.push(this._bumpTexture);
  41137. }
  41138. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41139. results.push(this._lightmapTexture);
  41140. }
  41141. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41142. results.push(this._refractionTexture);
  41143. }
  41144. return results;
  41145. };
  41146. /**
  41147. * Returns the texture used for reflections.
  41148. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41149. */
  41150. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41151. if (this._reflectionTexture) {
  41152. return this._reflectionTexture;
  41153. }
  41154. return this.getScene().environmentTexture;
  41155. };
  41156. /**
  41157. * Returns the texture used for refraction or null if none is used.
  41158. * @returns - Refection texture if present. If no refraction texture and refraction
  41159. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41160. */
  41161. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41162. if (this._refractionTexture) {
  41163. return this._refractionTexture;
  41164. }
  41165. if (this._linkRefractionWithTransparency) {
  41166. return this.getScene().environmentTexture;
  41167. }
  41168. return null;
  41169. };
  41170. /**
  41171. * Disposes the resources of the material.
  41172. * @param forceDisposeEffect - Forces the disposal of effects.
  41173. * @param forceDisposeTextures - Forces the disposal of all textures.
  41174. */
  41175. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41176. if (forceDisposeTextures) {
  41177. if (this._albedoTexture) {
  41178. this._albedoTexture.dispose();
  41179. }
  41180. if (this._ambientTexture) {
  41181. this._ambientTexture.dispose();
  41182. }
  41183. if (this._opacityTexture) {
  41184. this._opacityTexture.dispose();
  41185. }
  41186. if (this._reflectionTexture) {
  41187. this._reflectionTexture.dispose();
  41188. }
  41189. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41190. this._environmentBRDFTexture.dispose();
  41191. }
  41192. if (this._emissiveTexture) {
  41193. this._emissiveTexture.dispose();
  41194. }
  41195. if (this._metallicTexture) {
  41196. this._metallicTexture.dispose();
  41197. }
  41198. if (this._reflectivityTexture) {
  41199. this._reflectivityTexture.dispose();
  41200. }
  41201. if (this._bumpTexture) {
  41202. this._bumpTexture.dispose();
  41203. }
  41204. if (this._lightmapTexture) {
  41205. this._lightmapTexture.dispose();
  41206. }
  41207. if (this._refractionTexture) {
  41208. this._refractionTexture.dispose();
  41209. }
  41210. }
  41211. this._renderTargets.dispose();
  41212. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41213. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41214. }
  41215. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41216. };
  41217. /**
  41218. * Stores the reflectivity values based on metallic roughness workflow.
  41219. */
  41220. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41221. __decorate([
  41222. BABYLON.serializeAsImageProcessingConfiguration()
  41223. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41224. __decorate([
  41225. BABYLON.serialize()
  41226. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41227. __decorate([
  41228. BABYLON.serialize()
  41229. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41230. return PBRBaseMaterial;
  41231. }(BABYLON.PushMaterial));
  41232. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41233. })(BABYLON || (BABYLON = {}));
  41234. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41235. var BABYLON;
  41236. (function (BABYLON) {
  41237. /**
  41238. * The Physically based simple base material of BJS.
  41239. *
  41240. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41241. * It is used as the base class for both the specGloss and metalRough conventions.
  41242. */
  41243. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41244. __extends(PBRBaseSimpleMaterial, _super);
  41245. /**
  41246. * Instantiates a new PBRMaterial instance.
  41247. *
  41248. * @param name The material name
  41249. * @param scene The scene the material will be use in.
  41250. */
  41251. function PBRBaseSimpleMaterial(name, scene) {
  41252. var _this = _super.call(this, name, scene) || this;
  41253. /**
  41254. * Number of Simultaneous lights allowed on the material.
  41255. */
  41256. _this.maxSimultaneousLights = 4;
  41257. /**
  41258. * If sets to true, disables all the lights affecting the material.
  41259. */
  41260. _this.disableLighting = false;
  41261. /**
  41262. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41263. */
  41264. _this.invertNormalMapX = false;
  41265. /**
  41266. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41267. */
  41268. _this.invertNormalMapY = false;
  41269. /**
  41270. * Emissivie color used to self-illuminate the model.
  41271. */
  41272. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41273. /**
  41274. * Occlusion Channel Strenght.
  41275. */
  41276. _this.occlusionStrength = 1.0;
  41277. _this.useLightmapAsShadowmap = false;
  41278. _this._useAlphaFromAlbedoTexture = true;
  41279. _this._useAmbientInGrayScale = true;
  41280. return _this;
  41281. }
  41282. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41283. /**
  41284. * Gets the current double sided mode.
  41285. */
  41286. get: function () {
  41287. return this._twoSidedLighting;
  41288. },
  41289. /**
  41290. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41291. */
  41292. set: function (value) {
  41293. if (this._twoSidedLighting === value) {
  41294. return;
  41295. }
  41296. this._twoSidedLighting = value;
  41297. this.backFaceCulling = !value;
  41298. this._markAllSubMeshesAsTexturesDirty();
  41299. },
  41300. enumerable: true,
  41301. configurable: true
  41302. });
  41303. /**
  41304. * Return the active textures of the material.
  41305. */
  41306. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41307. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41308. if (this.environmentTexture) {
  41309. activeTextures.push(this.environmentTexture);
  41310. }
  41311. if (this.normalTexture) {
  41312. activeTextures.push(this.normalTexture);
  41313. }
  41314. if (this.emissiveTexture) {
  41315. activeTextures.push(this.emissiveTexture);
  41316. }
  41317. if (this.occlusionTexture) {
  41318. activeTextures.push(this.occlusionTexture);
  41319. }
  41320. if (this.lightmapTexture) {
  41321. activeTextures.push(this.lightmapTexture);
  41322. }
  41323. return activeTextures;
  41324. };
  41325. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41326. if (_super.prototype.hasTexture.call(this, texture)) {
  41327. return true;
  41328. }
  41329. if (this.lightmapTexture === texture) {
  41330. return true;
  41331. }
  41332. return false;
  41333. };
  41334. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41335. return "PBRBaseSimpleMaterial";
  41336. };
  41337. __decorate([
  41338. BABYLON.serialize(),
  41339. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41340. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41341. __decorate([
  41342. BABYLON.serialize(),
  41343. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41344. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41345. __decorate([
  41346. BABYLON.serializeAsTexture(),
  41347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41348. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41349. __decorate([
  41350. BABYLON.serialize(),
  41351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41352. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41353. __decorate([
  41354. BABYLON.serialize(),
  41355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41356. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41357. __decorate([
  41358. BABYLON.serializeAsTexture(),
  41359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41360. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41361. __decorate([
  41362. BABYLON.serializeAsColor3("emissive"),
  41363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41364. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41365. __decorate([
  41366. BABYLON.serializeAsTexture(),
  41367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41368. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41369. __decorate([
  41370. BABYLON.serialize(),
  41371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41372. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41373. __decorate([
  41374. BABYLON.serializeAsTexture(),
  41375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41376. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41377. __decorate([
  41378. BABYLON.serialize(),
  41379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41380. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41381. __decorate([
  41382. BABYLON.serialize()
  41383. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41384. __decorate([
  41385. BABYLON.serializeAsTexture(),
  41386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41387. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41388. __decorate([
  41389. BABYLON.serialize(),
  41390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41391. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41392. return PBRBaseSimpleMaterial;
  41393. }(BABYLON.PBRBaseMaterial));
  41394. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41395. })(BABYLON || (BABYLON = {}));
  41396. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41397. var BABYLON;
  41398. (function (BABYLON) {
  41399. /**
  41400. * The Physically based material of BJS.
  41401. *
  41402. * This offers the main features of a standard PBR material.
  41403. * For more information, please refer to the documentation :
  41404. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41405. */
  41406. var PBRMaterial = /** @class */ (function (_super) {
  41407. __extends(PBRMaterial, _super);
  41408. /**
  41409. * Instantiates a new PBRMaterial instance.
  41410. *
  41411. * @param name The material name
  41412. * @param scene The scene the material will be use in.
  41413. */
  41414. function PBRMaterial(name, scene) {
  41415. var _this = _super.call(this, name, scene) || this;
  41416. /**
  41417. * Intensity of the direct lights e.g. the four lights available in your scene.
  41418. * This impacts both the direct diffuse and specular highlights.
  41419. */
  41420. _this.directIntensity = 1.0;
  41421. /**
  41422. * Intensity of the emissive part of the material.
  41423. * This helps controlling the emissive effect without modifying the emissive color.
  41424. */
  41425. _this.emissiveIntensity = 1.0;
  41426. /**
  41427. * Intensity of the environment e.g. how much the environment will light the object
  41428. * either through harmonics for rough material or through the refelction for shiny ones.
  41429. */
  41430. _this.environmentIntensity = 1.0;
  41431. /**
  41432. * This is a special control allowing the reduction of the specular highlights coming from the
  41433. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41434. */
  41435. _this.specularIntensity = 1.0;
  41436. /**
  41437. * Debug Control allowing disabling the bump map on this material.
  41438. */
  41439. _this.disableBumpMap = false;
  41440. /**
  41441. * AKA Occlusion Texture Intensity in other nomenclature.
  41442. */
  41443. _this.ambientTextureStrength = 1.0;
  41444. /**
  41445. * The color of a material in ambient lighting.
  41446. */
  41447. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41448. /**
  41449. * AKA Diffuse Color in other nomenclature.
  41450. */
  41451. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41452. /**
  41453. * AKA Specular Color in other nomenclature.
  41454. */
  41455. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41456. /**
  41457. * The color reflected from the material.
  41458. */
  41459. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41460. /**
  41461. * The color emitted from the material.
  41462. */
  41463. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41464. /**
  41465. * AKA Glossiness in other nomenclature.
  41466. */
  41467. _this.microSurface = 1.0;
  41468. /**
  41469. * source material index of refraction (IOR)' / 'destination material IOR.
  41470. */
  41471. _this.indexOfRefraction = 0.66;
  41472. /**
  41473. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41474. */
  41475. _this.invertRefractionY = false;
  41476. /**
  41477. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41478. * Materials half opaque for instance using refraction could benefit from this control.
  41479. */
  41480. _this.linkRefractionWithTransparency = false;
  41481. _this.useLightmapAsShadowmap = false;
  41482. /**
  41483. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41484. */
  41485. _this.useAlphaFromAlbedoTexture = false;
  41486. /**
  41487. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41488. */
  41489. _this.forceAlphaTest = false;
  41490. /**
  41491. * Defines the alpha limits in alpha test mode.
  41492. */
  41493. _this.alphaCutOff = 0.4;
  41494. /**
  41495. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41496. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41497. */
  41498. _this.useSpecularOverAlpha = true;
  41499. /**
  41500. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41501. */
  41502. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41503. /**
  41504. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41505. */
  41506. _this.useRoughnessFromMetallicTextureAlpha = true;
  41507. /**
  41508. * Specifies if the metallic texture contains the roughness information in its green channel.
  41509. */
  41510. _this.useRoughnessFromMetallicTextureGreen = false;
  41511. /**
  41512. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41513. */
  41514. _this.useMetallnessFromMetallicTextureBlue = false;
  41515. /**
  41516. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41517. */
  41518. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41519. /**
  41520. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41521. */
  41522. _this.useAmbientInGrayScale = false;
  41523. /**
  41524. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41525. * The material will try to infer what glossiness each pixel should be.
  41526. */
  41527. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41528. /**
  41529. * BJS is using an harcoded light falloff based on a manually sets up range.
  41530. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41531. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41532. */
  41533. _this.usePhysicalLightFalloff = true;
  41534. /**
  41535. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41536. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41537. */
  41538. _this.useRadianceOverAlpha = true;
  41539. /**
  41540. * Allows using an object space normal map (instead of tangent space).
  41541. */
  41542. _this.useObjectSpaceNormalMap = false;
  41543. /**
  41544. * Allows using the bump map in parallax mode.
  41545. */
  41546. _this.useParallax = false;
  41547. /**
  41548. * Allows using the bump map in parallax occlusion mode.
  41549. */
  41550. _this.useParallaxOcclusion = false;
  41551. /**
  41552. * Controls the scale bias of the parallax mode.
  41553. */
  41554. _this.parallaxScaleBias = 0.05;
  41555. /**
  41556. * If sets to true, disables all the lights affecting the material.
  41557. */
  41558. _this.disableLighting = false;
  41559. /**
  41560. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41561. */
  41562. _this.forceIrradianceInFragment = false;
  41563. /**
  41564. * Number of Simultaneous lights allowed on the material.
  41565. */
  41566. _this.maxSimultaneousLights = 4;
  41567. /**
  41568. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41569. */
  41570. _this.invertNormalMapX = false;
  41571. /**
  41572. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41573. */
  41574. _this.invertNormalMapY = false;
  41575. /**
  41576. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41577. */
  41578. _this.twoSidedLighting = false;
  41579. /**
  41580. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41581. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41582. */
  41583. _this.useAlphaFresnel = false;
  41584. /**
  41585. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41586. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41587. */
  41588. _this.useLinearAlphaFresnel = false;
  41589. /**
  41590. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41591. * And/Or occlude the blended part.
  41592. */
  41593. _this.environmentBRDFTexture = null;
  41594. /**
  41595. * Force normal to face away from face.
  41596. */
  41597. _this.forceNormalForward = false;
  41598. /**
  41599. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41600. * makes the reflect vector face the model (under horizon).
  41601. */
  41602. _this.useHorizonOcclusion = true;
  41603. /**
  41604. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41605. * too much the area relying on ambient texture to define their ambient occlusion.
  41606. */
  41607. _this.useRadianceOcclusion = true;
  41608. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41609. return _this;
  41610. }
  41611. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41612. /**
  41613. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41614. */
  41615. get: function () {
  41616. return this._PBRMATERIAL_OPAQUE;
  41617. },
  41618. enumerable: true,
  41619. configurable: true
  41620. });
  41621. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41622. /**
  41623. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41624. */
  41625. get: function () {
  41626. return this._PBRMATERIAL_ALPHATEST;
  41627. },
  41628. enumerable: true,
  41629. configurable: true
  41630. });
  41631. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41632. /**
  41633. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41634. */
  41635. get: function () {
  41636. return this._PBRMATERIAL_ALPHABLEND;
  41637. },
  41638. enumerable: true,
  41639. configurable: true
  41640. });
  41641. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41642. /**
  41643. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41644. * They are also discarded below the alpha cutoff threshold to improve performances.
  41645. */
  41646. get: function () {
  41647. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41648. },
  41649. enumerable: true,
  41650. configurable: true
  41651. });
  41652. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41653. /**
  41654. * Gets the image processing configuration used either in this material.
  41655. */
  41656. get: function () {
  41657. return this._imageProcessingConfiguration;
  41658. },
  41659. /**
  41660. * Sets the Default image processing configuration used either in the this material.
  41661. *
  41662. * If sets to null, the scene one is in use.
  41663. */
  41664. set: function (value) {
  41665. this._attachImageProcessingConfiguration(value);
  41666. // Ensure the effect will be rebuilt.
  41667. this._markAllSubMeshesAsTexturesDirty();
  41668. },
  41669. enumerable: true,
  41670. configurable: true
  41671. });
  41672. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41673. /**
  41674. * Gets wether the color curves effect is enabled.
  41675. */
  41676. get: function () {
  41677. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41678. },
  41679. /**
  41680. * Sets wether the color curves effect is enabled.
  41681. */
  41682. set: function (value) {
  41683. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41684. },
  41685. enumerable: true,
  41686. configurable: true
  41687. });
  41688. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  41689. /**
  41690. * Gets wether the color grading effect is enabled.
  41691. */
  41692. get: function () {
  41693. return this.imageProcessingConfiguration.colorGradingEnabled;
  41694. },
  41695. /**
  41696. * Gets wether the color grading effect is enabled.
  41697. */
  41698. set: function (value) {
  41699. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41700. },
  41701. enumerable: true,
  41702. configurable: true
  41703. });
  41704. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  41705. /**
  41706. * Gets wether tonemapping is enabled or not.
  41707. */
  41708. get: function () {
  41709. return this._imageProcessingConfiguration.toneMappingEnabled;
  41710. },
  41711. /**
  41712. * Sets wether tonemapping is enabled or not
  41713. */
  41714. set: function (value) {
  41715. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41716. },
  41717. enumerable: true,
  41718. configurable: true
  41719. });
  41720. ;
  41721. ;
  41722. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  41723. /**
  41724. * The camera exposure used on this material.
  41725. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41726. * This corresponds to a photographic exposure.
  41727. */
  41728. get: function () {
  41729. return this._imageProcessingConfiguration.exposure;
  41730. },
  41731. /**
  41732. * The camera exposure used on this material.
  41733. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41734. * This corresponds to a photographic exposure.
  41735. */
  41736. set: function (value) {
  41737. this._imageProcessingConfiguration.exposure = value;
  41738. },
  41739. enumerable: true,
  41740. configurable: true
  41741. });
  41742. ;
  41743. ;
  41744. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  41745. /**
  41746. * Gets The camera contrast used on this material.
  41747. */
  41748. get: function () {
  41749. return this._imageProcessingConfiguration.contrast;
  41750. },
  41751. /**
  41752. * Sets The camera contrast used on this material.
  41753. */
  41754. set: function (value) {
  41755. this._imageProcessingConfiguration.contrast = value;
  41756. },
  41757. enumerable: true,
  41758. configurable: true
  41759. });
  41760. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  41761. /**
  41762. * Gets the Color Grading 2D Lookup Texture.
  41763. */
  41764. get: function () {
  41765. return this._imageProcessingConfiguration.colorGradingTexture;
  41766. },
  41767. /**
  41768. * Sets the Color Grading 2D Lookup Texture.
  41769. */
  41770. set: function (value) {
  41771. this._imageProcessingConfiguration.colorGradingTexture = value;
  41772. },
  41773. enumerable: true,
  41774. configurable: true
  41775. });
  41776. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  41777. /**
  41778. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41779. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41780. * 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;
  41781. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41782. */
  41783. get: function () {
  41784. return this._imageProcessingConfiguration.colorCurves;
  41785. },
  41786. /**
  41787. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41788. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41789. * 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;
  41790. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41791. */
  41792. set: function (value) {
  41793. this._imageProcessingConfiguration.colorCurves = value;
  41794. },
  41795. enumerable: true,
  41796. configurable: true
  41797. });
  41798. /**
  41799. * Returns the name of this material class.
  41800. */
  41801. PBRMaterial.prototype.getClassName = function () {
  41802. return "PBRMaterial";
  41803. };
  41804. /**
  41805. * Returns an array of the actively used textures.
  41806. * @returns - Array of BaseTextures
  41807. */
  41808. PBRMaterial.prototype.getActiveTextures = function () {
  41809. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41810. if (this._albedoTexture) {
  41811. activeTextures.push(this._albedoTexture);
  41812. }
  41813. if (this._ambientTexture) {
  41814. activeTextures.push(this._ambientTexture);
  41815. }
  41816. if (this._opacityTexture) {
  41817. activeTextures.push(this._opacityTexture);
  41818. }
  41819. if (this._reflectionTexture) {
  41820. activeTextures.push(this._reflectionTexture);
  41821. }
  41822. if (this._emissiveTexture) {
  41823. activeTextures.push(this._emissiveTexture);
  41824. }
  41825. if (this._reflectivityTexture) {
  41826. activeTextures.push(this._reflectivityTexture);
  41827. }
  41828. if (this._metallicTexture) {
  41829. activeTextures.push(this._metallicTexture);
  41830. }
  41831. if (this._microSurfaceTexture) {
  41832. activeTextures.push(this._microSurfaceTexture);
  41833. }
  41834. if (this._bumpTexture) {
  41835. activeTextures.push(this._bumpTexture);
  41836. }
  41837. if (this._lightmapTexture) {
  41838. activeTextures.push(this._lightmapTexture);
  41839. }
  41840. if (this._refractionTexture) {
  41841. activeTextures.push(this._refractionTexture);
  41842. }
  41843. return activeTextures;
  41844. };
  41845. /**
  41846. * Checks to see if a texture is used in the material.
  41847. * @param texture - Base texture to use.
  41848. * @returns - Boolean specifying if a texture is used in the material.
  41849. */
  41850. PBRMaterial.prototype.hasTexture = function (texture) {
  41851. if (_super.prototype.hasTexture.call(this, texture)) {
  41852. return true;
  41853. }
  41854. if (this._albedoTexture === texture) {
  41855. return true;
  41856. }
  41857. if (this._ambientTexture === texture) {
  41858. return true;
  41859. }
  41860. if (this._opacityTexture === texture) {
  41861. return true;
  41862. }
  41863. if (this._reflectionTexture === texture) {
  41864. return true;
  41865. }
  41866. if (this._reflectivityTexture === texture) {
  41867. return true;
  41868. }
  41869. if (this._metallicTexture === texture) {
  41870. return true;
  41871. }
  41872. if (this._microSurfaceTexture === texture) {
  41873. return true;
  41874. }
  41875. if (this._bumpTexture === texture) {
  41876. return true;
  41877. }
  41878. if (this._lightmapTexture === texture) {
  41879. return true;
  41880. }
  41881. if (this._refractionTexture === texture) {
  41882. return true;
  41883. }
  41884. return false;
  41885. };
  41886. /**
  41887. * Makes a duplicate of the current material.
  41888. * @param name - name to use for the new material.
  41889. */
  41890. PBRMaterial.prototype.clone = function (name) {
  41891. var _this = this;
  41892. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  41893. clone.id = name;
  41894. clone.name = name;
  41895. return clone;
  41896. };
  41897. /**
  41898. * Serializes this PBR Material.
  41899. * @returns - An object with the serialized material.
  41900. */
  41901. PBRMaterial.prototype.serialize = function () {
  41902. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41903. serializationObject.customType = "BABYLON.PBRMaterial";
  41904. return serializationObject;
  41905. };
  41906. // Statics
  41907. /**
  41908. * Parses a PBR Material from a serialized object.
  41909. * @param source - Serialized object.
  41910. * @param scene - BJS scene instance.
  41911. * @param rootUrl - url for the scene object
  41912. * @returns - PBRMaterial
  41913. */
  41914. PBRMaterial.Parse = function (source, scene, rootUrl) {
  41915. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  41916. };
  41917. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  41918. /**
  41919. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41920. */
  41921. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  41922. /**
  41923. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41924. */
  41925. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  41926. /**
  41927. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41928. * They are also discarded below the alpha cutoff threshold to improve performances.
  41929. */
  41930. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  41931. __decorate([
  41932. BABYLON.serialize(),
  41933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41934. ], PBRMaterial.prototype, "directIntensity", void 0);
  41935. __decorate([
  41936. BABYLON.serialize(),
  41937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41938. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  41939. __decorate([
  41940. BABYLON.serialize(),
  41941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41942. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  41943. __decorate([
  41944. BABYLON.serialize(),
  41945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41946. ], PBRMaterial.prototype, "specularIntensity", void 0);
  41947. __decorate([
  41948. BABYLON.serialize(),
  41949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41950. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  41951. __decorate([
  41952. BABYLON.serializeAsTexture(),
  41953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41954. ], PBRMaterial.prototype, "albedoTexture", void 0);
  41955. __decorate([
  41956. BABYLON.serializeAsTexture(),
  41957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41958. ], PBRMaterial.prototype, "ambientTexture", void 0);
  41959. __decorate([
  41960. BABYLON.serialize(),
  41961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41962. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  41963. __decorate([
  41964. BABYLON.serializeAsTexture(),
  41965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41966. ], PBRMaterial.prototype, "opacityTexture", void 0);
  41967. __decorate([
  41968. BABYLON.serializeAsTexture(),
  41969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41970. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  41971. __decorate([
  41972. BABYLON.serializeAsTexture(),
  41973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41974. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  41975. __decorate([
  41976. BABYLON.serializeAsTexture(),
  41977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41978. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  41979. __decorate([
  41980. BABYLON.serializeAsTexture(),
  41981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41982. ], PBRMaterial.prototype, "metallicTexture", void 0);
  41983. __decorate([
  41984. BABYLON.serialize(),
  41985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41986. ], PBRMaterial.prototype, "metallic", void 0);
  41987. __decorate([
  41988. BABYLON.serialize(),
  41989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41990. ], PBRMaterial.prototype, "roughness", void 0);
  41991. __decorate([
  41992. BABYLON.serializeAsTexture(),
  41993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41994. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  41995. __decorate([
  41996. BABYLON.serializeAsTexture(),
  41997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41998. ], PBRMaterial.prototype, "bumpTexture", void 0);
  41999. __decorate([
  42000. BABYLON.serializeAsTexture(),
  42001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42002. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42003. __decorate([
  42004. BABYLON.serializeAsTexture(),
  42005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42006. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42007. __decorate([
  42008. BABYLON.serializeAsColor3("ambient"),
  42009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42010. ], PBRMaterial.prototype, "ambientColor", void 0);
  42011. __decorate([
  42012. BABYLON.serializeAsColor3("albedo"),
  42013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42014. ], PBRMaterial.prototype, "albedoColor", void 0);
  42015. __decorate([
  42016. BABYLON.serializeAsColor3("reflectivity"),
  42017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42018. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42019. __decorate([
  42020. BABYLON.serializeAsColor3("reflection"),
  42021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42022. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42023. __decorate([
  42024. BABYLON.serializeAsColor3("emissive"),
  42025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42026. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42027. __decorate([
  42028. BABYLON.serialize(),
  42029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42030. ], PBRMaterial.prototype, "microSurface", void 0);
  42031. __decorate([
  42032. BABYLON.serialize(),
  42033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42034. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42035. __decorate([
  42036. BABYLON.serialize(),
  42037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42038. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42039. __decorate([
  42040. BABYLON.serialize(),
  42041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42042. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42043. __decorate([
  42044. BABYLON.serialize(),
  42045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42046. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42047. __decorate([
  42048. BABYLON.serialize(),
  42049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42050. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42051. __decorate([
  42052. BABYLON.serialize(),
  42053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42054. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42055. __decorate([
  42056. BABYLON.serialize(),
  42057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42058. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42059. __decorate([
  42060. BABYLON.serialize(),
  42061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42062. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42063. __decorate([
  42064. BABYLON.serialize(),
  42065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42066. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42067. __decorate([
  42068. BABYLON.serialize(),
  42069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42070. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42071. __decorate([
  42072. BABYLON.serialize(),
  42073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42074. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42075. __decorate([
  42076. BABYLON.serialize(),
  42077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42078. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42079. __decorate([
  42080. BABYLON.serialize(),
  42081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42082. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42083. __decorate([
  42084. BABYLON.serialize(),
  42085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42086. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42087. __decorate([
  42088. BABYLON.serialize(),
  42089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42090. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42091. __decorate([
  42092. BABYLON.serialize(),
  42093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42094. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42095. __decorate([
  42096. BABYLON.serialize(),
  42097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42098. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42099. __decorate([
  42100. BABYLON.serialize(),
  42101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42102. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42103. __decorate([
  42104. BABYLON.serialize(),
  42105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42106. ], PBRMaterial.prototype, "useParallax", void 0);
  42107. __decorate([
  42108. BABYLON.serialize(),
  42109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42110. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42111. __decorate([
  42112. BABYLON.serialize(),
  42113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42114. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42115. __decorate([
  42116. BABYLON.serialize(),
  42117. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42118. ], PBRMaterial.prototype, "disableLighting", void 0);
  42119. __decorate([
  42120. BABYLON.serialize(),
  42121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42122. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42123. __decorate([
  42124. BABYLON.serialize(),
  42125. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42126. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42127. __decorate([
  42128. BABYLON.serialize(),
  42129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42130. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42131. __decorate([
  42132. BABYLON.serialize(),
  42133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42134. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42135. __decorate([
  42136. BABYLON.serialize(),
  42137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42138. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42139. __decorate([
  42140. BABYLON.serialize(),
  42141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42142. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42143. __decorate([
  42144. BABYLON.serialize(),
  42145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42146. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42147. __decorate([
  42148. BABYLON.serializeAsTexture(),
  42149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42150. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42151. __decorate([
  42152. BABYLON.serialize(),
  42153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42154. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42155. __decorate([
  42156. BABYLON.serialize(),
  42157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42158. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42159. __decorate([
  42160. BABYLON.serialize(),
  42161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42162. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42163. return PBRMaterial;
  42164. }(BABYLON.PBRBaseMaterial));
  42165. BABYLON.PBRMaterial = PBRMaterial;
  42166. })(BABYLON || (BABYLON = {}));
  42167. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42168. var BABYLON;
  42169. (function (BABYLON) {
  42170. /**
  42171. * The PBR material of BJS following the metal roughness convention.
  42172. *
  42173. * This fits to the PBR convention in the GLTF definition:
  42174. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42175. */
  42176. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42177. __extends(PBRMetallicRoughnessMaterial, _super);
  42178. /**
  42179. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42180. *
  42181. * @param name The material name
  42182. * @param scene The scene the material will be use in.
  42183. */
  42184. function PBRMetallicRoughnessMaterial(name, scene) {
  42185. var _this = _super.call(this, name, scene) || this;
  42186. _this._useRoughnessFromMetallicTextureAlpha = false;
  42187. _this._useRoughnessFromMetallicTextureGreen = true;
  42188. _this._useMetallnessFromMetallicTextureBlue = true;
  42189. _this._forceMetallicWorkflow = true;
  42190. return _this;
  42191. }
  42192. /**
  42193. * Return the currrent class name of the material.
  42194. */
  42195. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42196. return "PBRMetallicRoughnessMaterial";
  42197. };
  42198. /**
  42199. * Return the active textures of the material.
  42200. */
  42201. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42202. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42203. if (this.baseTexture) {
  42204. activeTextures.push(this.baseTexture);
  42205. }
  42206. if (this.metallicRoughnessTexture) {
  42207. activeTextures.push(this.metallicRoughnessTexture);
  42208. }
  42209. return activeTextures;
  42210. };
  42211. /**
  42212. * Checks to see if a texture is used in the material.
  42213. * @param texture - Base texture to use.
  42214. * @returns - Boolean specifying if a texture is used in the material.
  42215. */
  42216. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42217. if (_super.prototype.hasTexture.call(this, texture)) {
  42218. return true;
  42219. }
  42220. if (this.baseTexture === texture) {
  42221. return true;
  42222. }
  42223. if (this.metallicRoughnessTexture === texture) {
  42224. return true;
  42225. }
  42226. return false;
  42227. };
  42228. /**
  42229. * Makes a duplicate of the current material.
  42230. * @param name - name to use for the new material.
  42231. */
  42232. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42233. var _this = this;
  42234. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42235. clone.id = name;
  42236. clone.name = name;
  42237. return clone;
  42238. };
  42239. /**
  42240. * Serialize the material to a parsable JSON object.
  42241. */
  42242. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42243. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42244. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42245. return serializationObject;
  42246. };
  42247. /**
  42248. * Parses a JSON object correponding to the serialize function.
  42249. */
  42250. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42251. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42252. };
  42253. __decorate([
  42254. BABYLON.serializeAsColor3(),
  42255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42256. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42257. __decorate([
  42258. BABYLON.serializeAsTexture(),
  42259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42260. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42261. __decorate([
  42262. BABYLON.serialize(),
  42263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42264. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42265. __decorate([
  42266. BABYLON.serialize(),
  42267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42268. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42269. __decorate([
  42270. BABYLON.serializeAsTexture(),
  42271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42272. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42273. return PBRMetallicRoughnessMaterial;
  42274. }(BABYLON.PBRBaseSimpleMaterial));
  42275. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42276. })(BABYLON || (BABYLON = {}));
  42277. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42278. var BABYLON;
  42279. (function (BABYLON) {
  42280. /**
  42281. * The PBR material of BJS following the specular glossiness convention.
  42282. *
  42283. * This fits to the PBR convention in the GLTF definition:
  42284. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42285. */
  42286. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42287. __extends(PBRSpecularGlossinessMaterial, _super);
  42288. /**
  42289. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42290. *
  42291. * @param name The material name
  42292. * @param scene The scene the material will be use in.
  42293. */
  42294. function PBRSpecularGlossinessMaterial(name, scene) {
  42295. var _this = _super.call(this, name, scene) || this;
  42296. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42297. return _this;
  42298. }
  42299. /**
  42300. * Return the currrent class name of the material.
  42301. */
  42302. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42303. return "PBRSpecularGlossinessMaterial";
  42304. };
  42305. /**
  42306. * Return the active textures of the material.
  42307. */
  42308. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42309. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42310. if (this.diffuseTexture) {
  42311. activeTextures.push(this.diffuseTexture);
  42312. }
  42313. if (this.specularGlossinessTexture) {
  42314. activeTextures.push(this.specularGlossinessTexture);
  42315. }
  42316. return activeTextures;
  42317. };
  42318. /**
  42319. * Checks to see if a texture is used in the material.
  42320. * @param texture - Base texture to use.
  42321. * @returns - Boolean specifying if a texture is used in the material.
  42322. */
  42323. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42324. if (_super.prototype.hasTexture.call(this, texture)) {
  42325. return true;
  42326. }
  42327. if (this.diffuseTexture === texture) {
  42328. return true;
  42329. }
  42330. if (this.specularGlossinessTexture === texture) {
  42331. return true;
  42332. }
  42333. return false;
  42334. };
  42335. /**
  42336. * Makes a duplicate of the current material.
  42337. * @param name - name to use for the new material.
  42338. */
  42339. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42340. var _this = this;
  42341. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42342. clone.id = name;
  42343. clone.name = name;
  42344. return clone;
  42345. };
  42346. /**
  42347. * Serialize the material to a parsable JSON object.
  42348. */
  42349. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42350. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42351. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42352. return serializationObject;
  42353. };
  42354. /**
  42355. * Parses a JSON object correponding to the serialize function.
  42356. */
  42357. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42358. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42359. };
  42360. __decorate([
  42361. BABYLON.serializeAsColor3("diffuse"),
  42362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42363. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42364. __decorate([
  42365. BABYLON.serializeAsTexture(),
  42366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42367. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42368. __decorate([
  42369. BABYLON.serializeAsColor3("specular"),
  42370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42371. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42372. __decorate([
  42373. BABYLON.serialize(),
  42374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42375. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42376. __decorate([
  42377. BABYLON.serializeAsTexture(),
  42378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42379. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42380. return PBRSpecularGlossinessMaterial;
  42381. }(BABYLON.PBRBaseSimpleMaterial));
  42382. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42383. })(BABYLON || (BABYLON = {}));
  42384. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42385. var BABYLON;
  42386. (function (BABYLON) {
  42387. BABYLON.CameraInputTypes = {};
  42388. var CameraInputsManager = /** @class */ (function () {
  42389. function CameraInputsManager(camera) {
  42390. this.attached = {};
  42391. this.camera = camera;
  42392. this.checkInputs = function () { };
  42393. }
  42394. /**
  42395. * Add an input method to a camera.
  42396. * builtin inputs example: camera.inputs.addGamepad();
  42397. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42398. * @param input camera input method
  42399. */
  42400. CameraInputsManager.prototype.add = function (input) {
  42401. var type = input.getSimpleName();
  42402. if (this.attached[type]) {
  42403. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42404. return;
  42405. }
  42406. this.attached[type] = input;
  42407. input.camera = this.camera;
  42408. //for checkInputs, we are dynamically creating a function
  42409. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42410. if (input.checkInputs) {
  42411. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42412. }
  42413. if (this.attachedElement) {
  42414. input.attachControl(this.attachedElement);
  42415. }
  42416. };
  42417. /**
  42418. * Remove a specific input method from a camera
  42419. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42420. * @param inputToRemove camera input method
  42421. */
  42422. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42423. for (var cam in this.attached) {
  42424. var input = this.attached[cam];
  42425. if (input === inputToRemove) {
  42426. input.detachControl(this.attachedElement);
  42427. input.camera = null;
  42428. delete this.attached[cam];
  42429. this.rebuildInputCheck();
  42430. }
  42431. }
  42432. };
  42433. CameraInputsManager.prototype.removeByType = function (inputType) {
  42434. for (var cam in this.attached) {
  42435. var input = this.attached[cam];
  42436. if (input.getClassName() === inputType) {
  42437. input.detachControl(this.attachedElement);
  42438. input.camera = null;
  42439. delete this.attached[cam];
  42440. this.rebuildInputCheck();
  42441. }
  42442. }
  42443. };
  42444. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42445. var current = this.checkInputs;
  42446. return function () {
  42447. current();
  42448. fn();
  42449. };
  42450. };
  42451. CameraInputsManager.prototype.attachInput = function (input) {
  42452. if (this.attachedElement) {
  42453. input.attachControl(this.attachedElement, this.noPreventDefault);
  42454. }
  42455. };
  42456. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42457. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42458. if (this.attachedElement) {
  42459. return;
  42460. }
  42461. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42462. this.attachedElement = element;
  42463. this.noPreventDefault = noPreventDefault;
  42464. for (var cam in this.attached) {
  42465. this.attached[cam].attachControl(element, noPreventDefault);
  42466. }
  42467. };
  42468. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42469. if (disconnect === void 0) { disconnect = false; }
  42470. if (this.attachedElement !== element) {
  42471. return;
  42472. }
  42473. for (var cam in this.attached) {
  42474. this.attached[cam].detachControl(element);
  42475. if (disconnect) {
  42476. this.attached[cam].camera = null;
  42477. }
  42478. }
  42479. this.attachedElement = null;
  42480. };
  42481. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42482. this.checkInputs = function () { };
  42483. for (var cam in this.attached) {
  42484. var input = this.attached[cam];
  42485. if (input.checkInputs) {
  42486. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42487. }
  42488. }
  42489. };
  42490. /**
  42491. * Remove all attached input methods from a camera
  42492. */
  42493. CameraInputsManager.prototype.clear = function () {
  42494. if (this.attachedElement) {
  42495. this.detachElement(this.attachedElement, true);
  42496. }
  42497. this.attached = {};
  42498. this.attachedElement = null;
  42499. this.checkInputs = function () { };
  42500. };
  42501. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42502. var inputs = {};
  42503. for (var cam in this.attached) {
  42504. var input = this.attached[cam];
  42505. var res = BABYLON.SerializationHelper.Serialize(input);
  42506. inputs[input.getClassName()] = res;
  42507. }
  42508. serializedCamera.inputsmgr = inputs;
  42509. };
  42510. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42511. var parsedInputs = parsedCamera.inputsmgr;
  42512. if (parsedInputs) {
  42513. this.clear();
  42514. for (var n in parsedInputs) {
  42515. var construct = BABYLON.CameraInputTypes[n];
  42516. if (construct) {
  42517. var parsedinput = parsedInputs[n];
  42518. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42519. this.add(input);
  42520. }
  42521. }
  42522. }
  42523. else {
  42524. //2016-03-08 this part is for managing backward compatibility
  42525. for (var n in this.attached) {
  42526. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42527. if (construct) {
  42528. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42529. this.remove(this.attached[n]);
  42530. this.add(input);
  42531. }
  42532. }
  42533. }
  42534. };
  42535. return CameraInputsManager;
  42536. }());
  42537. BABYLON.CameraInputsManager = CameraInputsManager;
  42538. })(BABYLON || (BABYLON = {}));
  42539. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42540. var BABYLON;
  42541. (function (BABYLON) {
  42542. var TargetCamera = /** @class */ (function (_super) {
  42543. __extends(TargetCamera, _super);
  42544. function TargetCamera(name, position, scene) {
  42545. var _this = _super.call(this, name, position, scene) || this;
  42546. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42547. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42548. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42549. _this.speed = 2.0;
  42550. _this.noRotationConstraint = false;
  42551. _this.lockedTarget = null;
  42552. _this._currentTarget = BABYLON.Vector3.Zero();
  42553. _this._viewMatrix = BABYLON.Matrix.Zero();
  42554. _this._camMatrix = BABYLON.Matrix.Zero();
  42555. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42556. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42557. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42558. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42559. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42560. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42561. _this._tempMatrix = BABYLON.Matrix.Zero();
  42562. return _this;
  42563. }
  42564. TargetCamera.prototype.getFrontPosition = function (distance) {
  42565. this.getWorldMatrix();
  42566. var direction = this.getTarget().subtract(this.position);
  42567. direction.normalize();
  42568. direction.scaleInPlace(distance);
  42569. return this.globalPosition.add(direction);
  42570. };
  42571. TargetCamera.prototype._getLockedTargetPosition = function () {
  42572. if (!this.lockedTarget) {
  42573. return null;
  42574. }
  42575. if (this.lockedTarget.absolutePosition) {
  42576. this.lockedTarget.computeWorldMatrix();
  42577. }
  42578. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42579. };
  42580. TargetCamera.prototype.storeState = function () {
  42581. this._storedPosition = this.position.clone();
  42582. this._storedRotation = this.rotation.clone();
  42583. if (this.rotationQuaternion) {
  42584. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42585. }
  42586. return _super.prototype.storeState.call(this);
  42587. };
  42588. /**
  42589. * Restored camera state. You must call storeState() first
  42590. */
  42591. TargetCamera.prototype._restoreStateValues = function () {
  42592. if (!_super.prototype._restoreStateValues.call(this)) {
  42593. return false;
  42594. }
  42595. this.position = this._storedPosition.clone();
  42596. this.rotation = this._storedRotation.clone();
  42597. if (this.rotationQuaternion) {
  42598. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42599. }
  42600. this.cameraDirection.copyFromFloats(0, 0, 0);
  42601. this.cameraRotation.copyFromFloats(0, 0);
  42602. return true;
  42603. };
  42604. // Cache
  42605. TargetCamera.prototype._initCache = function () {
  42606. _super.prototype._initCache.call(this);
  42607. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42608. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42609. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42610. };
  42611. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42612. if (!ignoreParentClass) {
  42613. _super.prototype._updateCache.call(this);
  42614. }
  42615. var lockedTargetPosition = this._getLockedTargetPosition();
  42616. if (!lockedTargetPosition) {
  42617. this._cache.lockedTarget = null;
  42618. }
  42619. else {
  42620. if (!this._cache.lockedTarget) {
  42621. this._cache.lockedTarget = lockedTargetPosition.clone();
  42622. }
  42623. else {
  42624. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42625. }
  42626. }
  42627. this._cache.rotation.copyFrom(this.rotation);
  42628. if (this.rotationQuaternion)
  42629. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42630. };
  42631. // Synchronized
  42632. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42633. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42634. return false;
  42635. }
  42636. var lockedTargetPosition = this._getLockedTargetPosition();
  42637. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42638. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42639. };
  42640. // Methods
  42641. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42642. var engine = this.getEngine();
  42643. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42644. };
  42645. // Target
  42646. TargetCamera.prototype.setTarget = function (target) {
  42647. this.upVector.normalize();
  42648. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42649. this._camMatrix.invert();
  42650. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42651. var vDir = target.subtract(this.position);
  42652. if (vDir.x >= 0.0) {
  42653. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42654. }
  42655. else {
  42656. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42657. }
  42658. this.rotation.z = 0;
  42659. if (isNaN(this.rotation.x)) {
  42660. this.rotation.x = 0;
  42661. }
  42662. if (isNaN(this.rotation.y)) {
  42663. this.rotation.y = 0;
  42664. }
  42665. if (isNaN(this.rotation.z)) {
  42666. this.rotation.z = 0;
  42667. }
  42668. if (this.rotationQuaternion) {
  42669. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42670. }
  42671. };
  42672. /**
  42673. * Return the current target position of the camera. This value is expressed in local space.
  42674. */
  42675. TargetCamera.prototype.getTarget = function () {
  42676. return this._currentTarget;
  42677. };
  42678. TargetCamera.prototype._decideIfNeedsToMove = function () {
  42679. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42680. };
  42681. TargetCamera.prototype._updatePosition = function () {
  42682. if (this.parent) {
  42683. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  42684. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  42685. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  42686. return;
  42687. }
  42688. this.position.addInPlace(this.cameraDirection);
  42689. };
  42690. TargetCamera.prototype._checkInputs = function () {
  42691. var needToMove = this._decideIfNeedsToMove();
  42692. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  42693. // Move
  42694. if (needToMove) {
  42695. this._updatePosition();
  42696. }
  42697. // Rotate
  42698. if (needToRotate) {
  42699. this.rotation.x += this.cameraRotation.x;
  42700. this.rotation.y += this.cameraRotation.y;
  42701. //rotate, if quaternion is set and rotation was used
  42702. if (this.rotationQuaternion) {
  42703. var len = this.rotation.lengthSquared();
  42704. if (len) {
  42705. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42706. }
  42707. }
  42708. if (!this.noRotationConstraint) {
  42709. var limit = (Math.PI / 2) * 0.95;
  42710. if (this.rotation.x > limit)
  42711. this.rotation.x = limit;
  42712. if (this.rotation.x < -limit)
  42713. this.rotation.x = -limit;
  42714. }
  42715. }
  42716. // Inertia
  42717. if (needToMove) {
  42718. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  42719. this.cameraDirection.x = 0;
  42720. }
  42721. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  42722. this.cameraDirection.y = 0;
  42723. }
  42724. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  42725. this.cameraDirection.z = 0;
  42726. }
  42727. this.cameraDirection.scaleInPlace(this.inertia);
  42728. }
  42729. if (needToRotate) {
  42730. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  42731. this.cameraRotation.x = 0;
  42732. }
  42733. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  42734. this.cameraRotation.y = 0;
  42735. }
  42736. this.cameraRotation.scaleInPlace(this.inertia);
  42737. }
  42738. _super.prototype._checkInputs.call(this);
  42739. };
  42740. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  42741. if (this.rotationQuaternion) {
  42742. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  42743. }
  42744. else {
  42745. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  42746. }
  42747. //update the up vector!
  42748. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  42749. };
  42750. TargetCamera.prototype._getViewMatrix = function () {
  42751. if (this.lockedTarget) {
  42752. this.setTarget(this._getLockedTargetPosition());
  42753. }
  42754. // Compute
  42755. this._updateCameraRotationMatrix();
  42756. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  42757. // Computing target and final matrix
  42758. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  42759. if (this.getScene().useRightHandedSystem) {
  42760. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42761. }
  42762. else {
  42763. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42764. }
  42765. return this._viewMatrix;
  42766. };
  42767. /**
  42768. * @override
  42769. * Override Camera.createRigCamera
  42770. */
  42771. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42772. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  42773. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  42774. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  42775. if (!this.rotationQuaternion) {
  42776. this.rotationQuaternion = new BABYLON.Quaternion();
  42777. }
  42778. rigCamera._cameraRigParams = {};
  42779. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  42780. }
  42781. return rigCamera;
  42782. }
  42783. return null;
  42784. };
  42785. /**
  42786. * @override
  42787. * Override Camera._updateRigCameras
  42788. */
  42789. TargetCamera.prototype._updateRigCameras = function () {
  42790. var camLeft = this._rigCameras[0];
  42791. var camRight = this._rigCameras[1];
  42792. switch (this.cameraRigMode) {
  42793. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42794. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42795. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42796. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42797. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  42798. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  42799. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  42800. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  42801. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  42802. camLeft.setTarget(this.getTarget());
  42803. camRight.setTarget(this.getTarget());
  42804. break;
  42805. case BABYLON.Camera.RIG_MODE_VR:
  42806. if (camLeft.rotationQuaternion) {
  42807. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42808. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42809. }
  42810. else {
  42811. camLeft.rotation.copyFrom(this.rotation);
  42812. camRight.rotation.copyFrom(this.rotation);
  42813. }
  42814. camLeft.position.copyFrom(this.position);
  42815. camRight.position.copyFrom(this.position);
  42816. break;
  42817. }
  42818. _super.prototype._updateRigCameras.call(this);
  42819. };
  42820. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  42821. if (!this._rigCamTransformMatrix) {
  42822. this._rigCamTransformMatrix = new BABYLON.Matrix();
  42823. }
  42824. var target = this.getTarget();
  42825. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  42826. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  42827. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  42828. };
  42829. TargetCamera.prototype.getClassName = function () {
  42830. return "TargetCamera";
  42831. };
  42832. __decorate([
  42833. BABYLON.serializeAsVector3()
  42834. ], TargetCamera.prototype, "rotation", void 0);
  42835. __decorate([
  42836. BABYLON.serialize()
  42837. ], TargetCamera.prototype, "speed", void 0);
  42838. __decorate([
  42839. BABYLON.serializeAsMeshReference("lockedTargetId")
  42840. ], TargetCamera.prototype, "lockedTarget", void 0);
  42841. return TargetCamera;
  42842. }(BABYLON.Camera));
  42843. BABYLON.TargetCamera = TargetCamera;
  42844. })(BABYLON || (BABYLON = {}));
  42845. //# sourceMappingURL=babylon.targetCamera.js.map
  42846. var BABYLON;
  42847. (function (BABYLON) {
  42848. var FreeCameraMouseInput = /** @class */ (function () {
  42849. function FreeCameraMouseInput(touchEnabled) {
  42850. if (touchEnabled === void 0) { touchEnabled = true; }
  42851. this.touchEnabled = touchEnabled;
  42852. this.buttons = [0, 1, 2];
  42853. this.angularSensibility = 2000.0;
  42854. this.previousPosition = null;
  42855. }
  42856. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  42857. var _this = this;
  42858. var engine = this.camera.getEngine();
  42859. if (!this._pointerInput) {
  42860. this._pointerInput = function (p, s) {
  42861. var evt = p.event;
  42862. if (engine.isInVRExclusivePointerMode) {
  42863. return;
  42864. }
  42865. if (!_this.touchEnabled && evt.pointerType === "touch") {
  42866. return;
  42867. }
  42868. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  42869. return;
  42870. }
  42871. var srcElement = (evt.srcElement || evt.target);
  42872. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  42873. try {
  42874. srcElement.setPointerCapture(evt.pointerId);
  42875. }
  42876. catch (e) {
  42877. //Nothing to do with the error. Execution will continue.
  42878. }
  42879. _this.previousPosition = {
  42880. x: evt.clientX,
  42881. y: evt.clientY
  42882. };
  42883. if (!noPreventDefault) {
  42884. evt.preventDefault();
  42885. element.focus();
  42886. }
  42887. }
  42888. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  42889. try {
  42890. srcElement.releasePointerCapture(evt.pointerId);
  42891. }
  42892. catch (e) {
  42893. //Nothing to do with the error.
  42894. }
  42895. _this.previousPosition = null;
  42896. if (!noPreventDefault) {
  42897. evt.preventDefault();
  42898. }
  42899. }
  42900. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  42901. if (!_this.previousPosition || engine.isPointerLock) {
  42902. return;
  42903. }
  42904. var offsetX = evt.clientX - _this.previousPosition.x;
  42905. var offsetY = evt.clientY - _this.previousPosition.y;
  42906. if (_this.camera.getScene().useRightHandedSystem) {
  42907. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42908. }
  42909. else {
  42910. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42911. }
  42912. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42913. _this.previousPosition = {
  42914. x: evt.clientX,
  42915. y: evt.clientY
  42916. };
  42917. if (!noPreventDefault) {
  42918. evt.preventDefault();
  42919. }
  42920. }
  42921. };
  42922. }
  42923. this._onMouseMove = function (evt) {
  42924. if (!engine.isPointerLock) {
  42925. return;
  42926. }
  42927. if (engine.isInVRExclusivePointerMode) {
  42928. return;
  42929. }
  42930. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42931. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42932. if (_this.camera.getScene().useRightHandedSystem) {
  42933. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42934. }
  42935. else {
  42936. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42937. }
  42938. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42939. _this.previousPosition = null;
  42940. if (!noPreventDefault) {
  42941. evt.preventDefault();
  42942. }
  42943. };
  42944. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  42945. element.addEventListener("mousemove", this._onMouseMove, false);
  42946. };
  42947. FreeCameraMouseInput.prototype.detachControl = function (element) {
  42948. if (this._observer && element) {
  42949. this.camera.getScene().onPointerObservable.remove(this._observer);
  42950. if (this._onMouseMove) {
  42951. element.removeEventListener("mousemove", this._onMouseMove);
  42952. }
  42953. this._observer = null;
  42954. this._onMouseMove = null;
  42955. this.previousPosition = null;
  42956. }
  42957. };
  42958. FreeCameraMouseInput.prototype.getClassName = function () {
  42959. return "FreeCameraMouseInput";
  42960. };
  42961. FreeCameraMouseInput.prototype.getSimpleName = function () {
  42962. return "mouse";
  42963. };
  42964. __decorate([
  42965. BABYLON.serialize()
  42966. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  42967. __decorate([
  42968. BABYLON.serialize()
  42969. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  42970. return FreeCameraMouseInput;
  42971. }());
  42972. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  42973. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  42974. })(BABYLON || (BABYLON = {}));
  42975. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  42976. var BABYLON;
  42977. (function (BABYLON) {
  42978. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  42979. function FreeCameraKeyboardMoveInput() {
  42980. this._keys = new Array();
  42981. this.keysUp = [38];
  42982. this.keysDown = [40];
  42983. this.keysLeft = [37];
  42984. this.keysRight = [39];
  42985. }
  42986. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  42987. var _this = this;
  42988. if (this._onCanvasBlurObserver) {
  42989. return;
  42990. }
  42991. this._scene = this.camera.getScene();
  42992. this._engine = this._scene.getEngine();
  42993. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  42994. _this._keys = [];
  42995. });
  42996. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  42997. var evt = info.event;
  42998. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  42999. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43000. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43001. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43002. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43003. var index = _this._keys.indexOf(evt.keyCode);
  43004. if (index === -1) {
  43005. _this._keys.push(evt.keyCode);
  43006. }
  43007. if (!noPreventDefault) {
  43008. evt.preventDefault();
  43009. }
  43010. }
  43011. }
  43012. else {
  43013. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43014. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43015. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43016. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43017. var index = _this._keys.indexOf(evt.keyCode);
  43018. if (index >= 0) {
  43019. _this._keys.splice(index, 1);
  43020. }
  43021. if (!noPreventDefault) {
  43022. evt.preventDefault();
  43023. }
  43024. }
  43025. }
  43026. });
  43027. };
  43028. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43029. if (this._scene) {
  43030. if (this._onKeyboardObserver) {
  43031. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43032. }
  43033. if (this._onCanvasBlurObserver) {
  43034. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43035. }
  43036. this._onKeyboardObserver = null;
  43037. this._onCanvasBlurObserver = null;
  43038. }
  43039. this._keys = [];
  43040. };
  43041. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43042. if (this._onKeyboardObserver) {
  43043. var camera = this.camera;
  43044. // Keyboard
  43045. for (var index = 0; index < this._keys.length; index++) {
  43046. var keyCode = this._keys[index];
  43047. var speed = camera._computeLocalCameraSpeed();
  43048. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43049. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43050. }
  43051. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43052. camera._localDirection.copyFromFloats(0, 0, speed);
  43053. }
  43054. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43055. camera._localDirection.copyFromFloats(speed, 0, 0);
  43056. }
  43057. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43058. camera._localDirection.copyFromFloats(0, 0, -speed);
  43059. }
  43060. if (camera.getScene().useRightHandedSystem) {
  43061. camera._localDirection.z *= -1;
  43062. }
  43063. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43064. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43065. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43066. }
  43067. }
  43068. };
  43069. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43070. return "FreeCameraKeyboardMoveInput";
  43071. };
  43072. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43073. this._keys = [];
  43074. };
  43075. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43076. return "keyboard";
  43077. };
  43078. __decorate([
  43079. BABYLON.serialize()
  43080. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43081. __decorate([
  43082. BABYLON.serialize()
  43083. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43084. __decorate([
  43085. BABYLON.serialize()
  43086. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43087. __decorate([
  43088. BABYLON.serialize()
  43089. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43090. return FreeCameraKeyboardMoveInput;
  43091. }());
  43092. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43093. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43094. })(BABYLON || (BABYLON = {}));
  43095. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43096. var BABYLON;
  43097. (function (BABYLON) {
  43098. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43099. __extends(FreeCameraInputsManager, _super);
  43100. function FreeCameraInputsManager(camera) {
  43101. return _super.call(this, camera) || this;
  43102. }
  43103. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43104. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43105. return this;
  43106. };
  43107. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43108. if (touchEnabled === void 0) { touchEnabled = true; }
  43109. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43110. return this;
  43111. };
  43112. FreeCameraInputsManager.prototype.addGamepad = function () {
  43113. this.add(new BABYLON.FreeCameraGamepadInput());
  43114. return this;
  43115. };
  43116. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43117. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43118. return this;
  43119. };
  43120. FreeCameraInputsManager.prototype.addTouch = function () {
  43121. this.add(new BABYLON.FreeCameraTouchInput());
  43122. return this;
  43123. };
  43124. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43125. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43126. return this;
  43127. };
  43128. return FreeCameraInputsManager;
  43129. }(BABYLON.CameraInputsManager));
  43130. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43131. })(BABYLON || (BABYLON = {}));
  43132. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43133. var BABYLON;
  43134. (function (BABYLON) {
  43135. var FreeCamera = /** @class */ (function (_super) {
  43136. __extends(FreeCamera, _super);
  43137. function FreeCamera(name, position, scene) {
  43138. var _this = _super.call(this, name, position, scene) || this;
  43139. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43140. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43141. _this.checkCollisions = false;
  43142. _this.applyGravity = false;
  43143. _this._needMoveForGravity = false;
  43144. _this._oldPosition = BABYLON.Vector3.Zero();
  43145. _this._diffPosition = BABYLON.Vector3.Zero();
  43146. _this._newPosition = BABYLON.Vector3.Zero();
  43147. // Collisions
  43148. _this._collisionMask = -1;
  43149. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43150. if (collidedMesh === void 0) { collidedMesh = null; }
  43151. //TODO move this to the collision coordinator!
  43152. if (_this.getScene().workerCollisions)
  43153. newPosition.multiplyInPlace(_this._collider._radius);
  43154. var updatePosition = function (newPos) {
  43155. _this._newPosition.copyFrom(newPos);
  43156. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43157. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43158. _this.position.addInPlace(_this._diffPosition);
  43159. if (_this.onCollide && collidedMesh) {
  43160. _this.onCollide(collidedMesh);
  43161. }
  43162. }
  43163. };
  43164. updatePosition(newPosition);
  43165. };
  43166. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43167. _this.inputs.addKeyboard().addMouse();
  43168. return _this;
  43169. }
  43170. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43171. //-- begin properties for backward compatibility for inputs
  43172. /**
  43173. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43174. * Higher values reduce sensitivity.
  43175. */
  43176. get: function () {
  43177. var mouse = this.inputs.attached["mouse"];
  43178. if (mouse)
  43179. return mouse.angularSensibility;
  43180. return 0;
  43181. },
  43182. /**
  43183. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43184. * Higher values reduce sensitivity.
  43185. */
  43186. set: function (value) {
  43187. var mouse = this.inputs.attached["mouse"];
  43188. if (mouse)
  43189. mouse.angularSensibility = value;
  43190. },
  43191. enumerable: true,
  43192. configurable: true
  43193. });
  43194. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43195. get: function () {
  43196. var keyboard = this.inputs.attached["keyboard"];
  43197. if (keyboard)
  43198. return keyboard.keysUp;
  43199. return [];
  43200. },
  43201. set: function (value) {
  43202. var keyboard = this.inputs.attached["keyboard"];
  43203. if (keyboard)
  43204. keyboard.keysUp = value;
  43205. },
  43206. enumerable: true,
  43207. configurable: true
  43208. });
  43209. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43210. get: function () {
  43211. var keyboard = this.inputs.attached["keyboard"];
  43212. if (keyboard)
  43213. return keyboard.keysDown;
  43214. return [];
  43215. },
  43216. set: function (value) {
  43217. var keyboard = this.inputs.attached["keyboard"];
  43218. if (keyboard)
  43219. keyboard.keysDown = value;
  43220. },
  43221. enumerable: true,
  43222. configurable: true
  43223. });
  43224. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43225. get: function () {
  43226. var keyboard = this.inputs.attached["keyboard"];
  43227. if (keyboard)
  43228. return keyboard.keysLeft;
  43229. return [];
  43230. },
  43231. set: function (value) {
  43232. var keyboard = this.inputs.attached["keyboard"];
  43233. if (keyboard)
  43234. keyboard.keysLeft = value;
  43235. },
  43236. enumerable: true,
  43237. configurable: true
  43238. });
  43239. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43240. get: function () {
  43241. var keyboard = this.inputs.attached["keyboard"];
  43242. if (keyboard)
  43243. return keyboard.keysRight;
  43244. return [];
  43245. },
  43246. set: function (value) {
  43247. var keyboard = this.inputs.attached["keyboard"];
  43248. if (keyboard)
  43249. keyboard.keysRight = value;
  43250. },
  43251. enumerable: true,
  43252. configurable: true
  43253. });
  43254. // Controls
  43255. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43256. this.inputs.attachElement(element, noPreventDefault);
  43257. };
  43258. FreeCamera.prototype.detachControl = function (element) {
  43259. this.inputs.detachElement(element);
  43260. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43261. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43262. };
  43263. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43264. get: function () {
  43265. return this._collisionMask;
  43266. },
  43267. set: function (mask) {
  43268. this._collisionMask = !isNaN(mask) ? mask : -1;
  43269. },
  43270. enumerable: true,
  43271. configurable: true
  43272. });
  43273. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43274. var globalPosition;
  43275. if (this.parent) {
  43276. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43277. }
  43278. else {
  43279. globalPosition = this.position;
  43280. }
  43281. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43282. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43283. if (!this._collider) {
  43284. this._collider = new BABYLON.Collider();
  43285. }
  43286. this._collider._radius = this.ellipsoid;
  43287. this._collider.collisionMask = this._collisionMask;
  43288. //no need for clone, as long as gravity is not on.
  43289. var actualDisplacement = displacement;
  43290. //add gravity to the direction to prevent the dual-collision checking
  43291. if (this.applyGravity) {
  43292. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43293. actualDisplacement = displacement.add(this.getScene().gravity);
  43294. }
  43295. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43296. };
  43297. FreeCamera.prototype._checkInputs = function () {
  43298. if (!this._localDirection) {
  43299. this._localDirection = BABYLON.Vector3.Zero();
  43300. this._transformedDirection = BABYLON.Vector3.Zero();
  43301. }
  43302. this.inputs.checkInputs();
  43303. _super.prototype._checkInputs.call(this);
  43304. };
  43305. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43306. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43307. };
  43308. FreeCamera.prototype._updatePosition = function () {
  43309. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43310. this._collideWithWorld(this.cameraDirection);
  43311. }
  43312. else {
  43313. _super.prototype._updatePosition.call(this);
  43314. }
  43315. };
  43316. FreeCamera.prototype.dispose = function () {
  43317. this.inputs.clear();
  43318. _super.prototype.dispose.call(this);
  43319. };
  43320. FreeCamera.prototype.getClassName = function () {
  43321. return "FreeCamera";
  43322. };
  43323. __decorate([
  43324. BABYLON.serializeAsVector3()
  43325. ], FreeCamera.prototype, "ellipsoid", void 0);
  43326. __decorate([
  43327. BABYLON.serializeAsVector3()
  43328. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43329. __decorate([
  43330. BABYLON.serialize()
  43331. ], FreeCamera.prototype, "checkCollisions", void 0);
  43332. __decorate([
  43333. BABYLON.serialize()
  43334. ], FreeCamera.prototype, "applyGravity", void 0);
  43335. return FreeCamera;
  43336. }(BABYLON.TargetCamera));
  43337. BABYLON.FreeCamera = FreeCamera;
  43338. })(BABYLON || (BABYLON = {}));
  43339. //# sourceMappingURL=babylon.freeCamera.js.map
  43340. var BABYLON;
  43341. (function (BABYLON) {
  43342. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43343. function ArcRotateCameraKeyboardMoveInput() {
  43344. this._keys = new Array();
  43345. this.keysUp = [38];
  43346. this.keysDown = [40];
  43347. this.keysLeft = [37];
  43348. this.keysRight = [39];
  43349. this.keysReset = [220];
  43350. this.panningSensibility = 50.0;
  43351. this.zoomingSensibility = 25.0;
  43352. this.useAltToZoom = true;
  43353. }
  43354. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43355. var _this = this;
  43356. if (this._onCanvasBlurObserver) {
  43357. return;
  43358. }
  43359. this._scene = this.camera.getScene();
  43360. this._engine = this._scene.getEngine();
  43361. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43362. _this._keys = [];
  43363. });
  43364. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43365. var evt = info.event;
  43366. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43367. _this._ctrlPressed = evt.ctrlKey;
  43368. _this._altPressed = evt.altKey;
  43369. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43370. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43371. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43372. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43373. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43374. var index = _this._keys.indexOf(evt.keyCode);
  43375. if (index === -1) {
  43376. _this._keys.push(evt.keyCode);
  43377. }
  43378. if (evt.preventDefault) {
  43379. if (!noPreventDefault) {
  43380. evt.preventDefault();
  43381. }
  43382. }
  43383. }
  43384. }
  43385. else {
  43386. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43387. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43388. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43389. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43390. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43391. var index = _this._keys.indexOf(evt.keyCode);
  43392. if (index >= 0) {
  43393. _this._keys.splice(index, 1);
  43394. }
  43395. if (evt.preventDefault) {
  43396. if (!noPreventDefault) {
  43397. evt.preventDefault();
  43398. }
  43399. }
  43400. }
  43401. }
  43402. });
  43403. };
  43404. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43405. if (this._scene) {
  43406. if (this._onKeyboardObserver) {
  43407. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43408. }
  43409. if (this._onCanvasBlurObserver) {
  43410. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43411. }
  43412. this._onKeyboardObserver = null;
  43413. this._onCanvasBlurObserver = null;
  43414. }
  43415. this._keys = [];
  43416. };
  43417. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43418. if (this._onKeyboardObserver) {
  43419. var camera = this.camera;
  43420. for (var index = 0; index < this._keys.length; index++) {
  43421. var keyCode = this._keys[index];
  43422. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43423. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43424. camera.inertialPanningX -= 1 / this.panningSensibility;
  43425. }
  43426. else {
  43427. camera.inertialAlphaOffset -= 0.01;
  43428. }
  43429. }
  43430. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43431. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43432. camera.inertialPanningY += 1 / this.panningSensibility;
  43433. }
  43434. else if (this._altPressed && this.useAltToZoom) {
  43435. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43436. }
  43437. else {
  43438. camera.inertialBetaOffset -= 0.01;
  43439. }
  43440. }
  43441. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43442. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43443. camera.inertialPanningX += 1 / this.panningSensibility;
  43444. }
  43445. else {
  43446. camera.inertialAlphaOffset += 0.01;
  43447. }
  43448. }
  43449. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43450. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43451. camera.inertialPanningY -= 1 / this.panningSensibility;
  43452. }
  43453. else if (this._altPressed && this.useAltToZoom) {
  43454. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43455. }
  43456. else {
  43457. camera.inertialBetaOffset += 0.01;
  43458. }
  43459. }
  43460. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43461. camera.restoreState();
  43462. }
  43463. }
  43464. }
  43465. };
  43466. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43467. return "ArcRotateCameraKeyboardMoveInput";
  43468. };
  43469. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43470. return "keyboard";
  43471. };
  43472. __decorate([
  43473. BABYLON.serialize()
  43474. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43475. __decorate([
  43476. BABYLON.serialize()
  43477. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43478. __decorate([
  43479. BABYLON.serialize()
  43480. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43481. __decorate([
  43482. BABYLON.serialize()
  43483. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43484. __decorate([
  43485. BABYLON.serialize()
  43486. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43487. __decorate([
  43488. BABYLON.serialize()
  43489. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43490. __decorate([
  43491. BABYLON.serialize()
  43492. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43493. __decorate([
  43494. BABYLON.serialize()
  43495. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43496. return ArcRotateCameraKeyboardMoveInput;
  43497. }());
  43498. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43499. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43500. })(BABYLON || (BABYLON = {}));
  43501. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43502. var BABYLON;
  43503. (function (BABYLON) {
  43504. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43505. function ArcRotateCameraMouseWheelInput() {
  43506. this.wheelPrecision = 3.0;
  43507. /**
  43508. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43509. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43510. */
  43511. this.wheelDeltaPercentage = 0;
  43512. }
  43513. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43514. var _this = this;
  43515. this._wheel = function (p, s) {
  43516. //sanity check - this should be a PointerWheel event.
  43517. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43518. return;
  43519. var event = p.event;
  43520. var delta = 0;
  43521. if (event.wheelDelta) {
  43522. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43523. }
  43524. else if (event.detail) {
  43525. delta = -event.detail / _this.wheelPrecision;
  43526. }
  43527. if (delta)
  43528. _this.camera.inertialRadiusOffset += delta;
  43529. if (event.preventDefault) {
  43530. if (!noPreventDefault) {
  43531. event.preventDefault();
  43532. }
  43533. }
  43534. };
  43535. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43536. };
  43537. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43538. if (this._observer && element) {
  43539. this.camera.getScene().onPointerObservable.remove(this._observer);
  43540. this._observer = null;
  43541. this._wheel = null;
  43542. }
  43543. };
  43544. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43545. return "ArcRotateCameraMouseWheelInput";
  43546. };
  43547. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43548. return "mousewheel";
  43549. };
  43550. __decorate([
  43551. BABYLON.serialize()
  43552. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43553. __decorate([
  43554. BABYLON.serialize()
  43555. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43556. return ArcRotateCameraMouseWheelInput;
  43557. }());
  43558. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43559. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43560. })(BABYLON || (BABYLON = {}));
  43561. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43562. var BABYLON;
  43563. (function (BABYLON) {
  43564. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43565. function ArcRotateCameraPointersInput() {
  43566. this.buttons = [0, 1, 2];
  43567. this.angularSensibilityX = 1000.0;
  43568. this.angularSensibilityY = 1000.0;
  43569. this.pinchPrecision = 12.0;
  43570. /**
  43571. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43572. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43573. */
  43574. this.pinchDeltaPercentage = 0;
  43575. this.panningSensibility = 1000.0;
  43576. this.multiTouchPanning = true;
  43577. this.multiTouchPanAndZoom = true;
  43578. this._isPanClick = false;
  43579. this.pinchInwards = true;
  43580. }
  43581. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43582. var _this = this;
  43583. var engine = this.camera.getEngine();
  43584. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43585. var pointA = null;
  43586. var pointB = null;
  43587. var previousPinchSquaredDistance = 0;
  43588. var initialDistance = 0;
  43589. var twoFingerActivityCount = 0;
  43590. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43591. this._pointerInput = function (p, s) {
  43592. var evt = p.event;
  43593. var isTouch = p.event.pointerType === "touch";
  43594. if (engine.isInVRExclusivePointerMode) {
  43595. return;
  43596. }
  43597. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43598. return;
  43599. }
  43600. var srcElement = (evt.srcElement || evt.target);
  43601. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43602. try {
  43603. srcElement.setPointerCapture(evt.pointerId);
  43604. }
  43605. catch (e) {
  43606. //Nothing to do with the error. Execution will continue.
  43607. }
  43608. // Manage panning with pan button click
  43609. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43610. // manage pointers
  43611. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43612. if (pointA === null) {
  43613. pointA = cacheSoloPointer;
  43614. }
  43615. else if (pointB === null) {
  43616. pointB = cacheSoloPointer;
  43617. }
  43618. if (!noPreventDefault) {
  43619. evt.preventDefault();
  43620. element.focus();
  43621. }
  43622. }
  43623. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43624. _this.camera.restoreState();
  43625. }
  43626. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43627. try {
  43628. srcElement.releasePointerCapture(evt.pointerId);
  43629. }
  43630. catch (e) {
  43631. //Nothing to do with the error.
  43632. }
  43633. cacheSoloPointer = null;
  43634. previousPinchSquaredDistance = 0;
  43635. previousMultiTouchPanPosition.isPaning = false;
  43636. previousMultiTouchPanPosition.isPinching = false;
  43637. twoFingerActivityCount = 0;
  43638. initialDistance = 0;
  43639. if (!isTouch) {
  43640. pointB = null; // Mouse and pen are mono pointer
  43641. }
  43642. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43643. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43644. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43645. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43646. if (engine.badOS) {
  43647. pointA = pointB = null;
  43648. }
  43649. else {
  43650. //only remove the impacted pointer in case of multitouch allowing on most
  43651. //platforms switching from rotate to zoom and pan seamlessly.
  43652. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43653. pointA = pointB;
  43654. pointB = null;
  43655. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43656. }
  43657. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43658. pointB = null;
  43659. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43660. }
  43661. else {
  43662. pointA = pointB = null;
  43663. }
  43664. }
  43665. if (!noPreventDefault) {
  43666. evt.preventDefault();
  43667. }
  43668. }
  43669. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43670. if (!noPreventDefault) {
  43671. evt.preventDefault();
  43672. }
  43673. // One button down
  43674. if (pointA && pointB === null && cacheSoloPointer) {
  43675. if (_this.panningSensibility !== 0 &&
  43676. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43677. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43678. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  43679. }
  43680. else {
  43681. var offsetX = evt.clientX - cacheSoloPointer.x;
  43682. var offsetY = evt.clientY - cacheSoloPointer.y;
  43683. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43684. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43685. }
  43686. cacheSoloPointer.x = evt.clientX;
  43687. cacheSoloPointer.y = evt.clientY;
  43688. }
  43689. else if (pointA && pointB) {
  43690. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  43691. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  43692. ed.x = evt.clientX;
  43693. ed.y = evt.clientY;
  43694. var direction = _this.pinchInwards ? 1 : -1;
  43695. var distX = pointA.x - pointB.x;
  43696. var distY = pointA.y - pointB.y;
  43697. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  43698. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  43699. if (previousPinchSquaredDistance === 0) {
  43700. initialDistance = pinchDistance;
  43701. previousPinchSquaredDistance = pinchSquaredDistance;
  43702. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  43703. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  43704. return;
  43705. }
  43706. if (_this.multiTouchPanAndZoom) {
  43707. if (_this.pinchDeltaPercentage) {
  43708. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43709. }
  43710. else {
  43711. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43712. (_this.pinchPrecision *
  43713. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43714. direction);
  43715. }
  43716. if (_this.panningSensibility !== 0) {
  43717. var pointersCenterX = (pointA.x + pointB.x) / 2;
  43718. var pointersCenterY = (pointA.y + pointB.y) / 2;
  43719. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  43720. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  43721. previousMultiTouchPanPosition.x = pointersCenterX;
  43722. previousMultiTouchPanPosition.y = pointersCenterY;
  43723. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  43724. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  43725. }
  43726. }
  43727. else {
  43728. twoFingerActivityCount++;
  43729. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  43730. if (_this.pinchDeltaPercentage) {
  43731. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43732. }
  43733. else {
  43734. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43735. (_this.pinchPrecision *
  43736. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43737. direction);
  43738. }
  43739. previousMultiTouchPanPosition.isPaning = false;
  43740. previousMultiTouchPanPosition.isPinching = true;
  43741. }
  43742. else {
  43743. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  43744. if (!previousMultiTouchPanPosition.isPaning) {
  43745. previousMultiTouchPanPosition.isPaning = true;
  43746. previousMultiTouchPanPosition.isPinching = false;
  43747. previousMultiTouchPanPosition.x = ed.x;
  43748. previousMultiTouchPanPosition.y = ed.y;
  43749. return;
  43750. }
  43751. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  43752. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  43753. }
  43754. }
  43755. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  43756. previousMultiTouchPanPosition.x = ed.x;
  43757. previousMultiTouchPanPosition.y = ed.y;
  43758. }
  43759. }
  43760. previousPinchSquaredDistance = pinchSquaredDistance;
  43761. }
  43762. }
  43763. };
  43764. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  43765. this._onContextMenu = function (evt) {
  43766. evt.preventDefault();
  43767. };
  43768. if (!this.camera._useCtrlForPanning) {
  43769. element.addEventListener("contextmenu", this._onContextMenu, false);
  43770. }
  43771. this._onLostFocus = function () {
  43772. //this._keys = [];
  43773. pointA = pointB = null;
  43774. previousPinchSquaredDistance = 0;
  43775. previousMultiTouchPanPosition.isPaning = false;
  43776. previousMultiTouchPanPosition.isPinching = false;
  43777. twoFingerActivityCount = 0;
  43778. cacheSoloPointer = null;
  43779. initialDistance = 0;
  43780. };
  43781. this._onMouseMove = function (evt) {
  43782. if (!engine.isPointerLock) {
  43783. return;
  43784. }
  43785. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43786. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43787. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43788. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43789. if (!noPreventDefault) {
  43790. evt.preventDefault();
  43791. }
  43792. };
  43793. this._onGestureStart = function (e) {
  43794. if (window.MSGesture === undefined) {
  43795. return;
  43796. }
  43797. if (!_this._MSGestureHandler) {
  43798. _this._MSGestureHandler = new MSGesture();
  43799. _this._MSGestureHandler.target = element;
  43800. }
  43801. _this._MSGestureHandler.addPointer(e.pointerId);
  43802. };
  43803. this._onGesture = function (e) {
  43804. _this.camera.radius *= e.scale;
  43805. if (e.preventDefault) {
  43806. if (!noPreventDefault) {
  43807. e.stopPropagation();
  43808. e.preventDefault();
  43809. }
  43810. }
  43811. };
  43812. element.addEventListener("mousemove", this._onMouseMove, false);
  43813. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  43814. element.addEventListener("MSGestureChange", this._onGesture, false);
  43815. BABYLON.Tools.RegisterTopRootEvents([
  43816. { name: "blur", handler: this._onLostFocus }
  43817. ]);
  43818. };
  43819. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  43820. if (this._onLostFocus) {
  43821. BABYLON.Tools.UnregisterTopRootEvents([
  43822. { name: "blur", handler: this._onLostFocus }
  43823. ]);
  43824. }
  43825. if (element && this._observer) {
  43826. this.camera.getScene().onPointerObservable.remove(this._observer);
  43827. this._observer = null;
  43828. if (this._onContextMenu) {
  43829. element.removeEventListener("contextmenu", this._onContextMenu);
  43830. }
  43831. if (this._onMouseMove) {
  43832. element.removeEventListener("mousemove", this._onMouseMove);
  43833. }
  43834. if (this._onGestureStart) {
  43835. element.removeEventListener("MSPointerDown", this._onGestureStart);
  43836. }
  43837. if (this._onGesture) {
  43838. element.removeEventListener("MSGestureChange", this._onGesture);
  43839. }
  43840. this._isPanClick = false;
  43841. this.pinchInwards = true;
  43842. this._onMouseMove = null;
  43843. this._onGestureStart = null;
  43844. this._onGesture = null;
  43845. this._MSGestureHandler = null;
  43846. this._onLostFocus = null;
  43847. this._onContextMenu = null;
  43848. }
  43849. };
  43850. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  43851. return "ArcRotateCameraPointersInput";
  43852. };
  43853. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  43854. return "pointers";
  43855. };
  43856. __decorate([
  43857. BABYLON.serialize()
  43858. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  43859. __decorate([
  43860. BABYLON.serialize()
  43861. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  43862. __decorate([
  43863. BABYLON.serialize()
  43864. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  43865. __decorate([
  43866. BABYLON.serialize()
  43867. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  43868. __decorate([
  43869. BABYLON.serialize()
  43870. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  43871. __decorate([
  43872. BABYLON.serialize()
  43873. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  43874. __decorate([
  43875. BABYLON.serialize()
  43876. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  43877. __decorate([
  43878. BABYLON.serialize()
  43879. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  43880. return ArcRotateCameraPointersInput;
  43881. }());
  43882. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  43883. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  43884. })(BABYLON || (BABYLON = {}));
  43885. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  43886. var BABYLON;
  43887. (function (BABYLON) {
  43888. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  43889. __extends(ArcRotateCameraInputsManager, _super);
  43890. function ArcRotateCameraInputsManager(camera) {
  43891. return _super.call(this, camera) || this;
  43892. }
  43893. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  43894. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  43895. return this;
  43896. };
  43897. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  43898. this.add(new BABYLON.ArcRotateCameraPointersInput());
  43899. return this;
  43900. };
  43901. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  43902. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  43903. return this;
  43904. };
  43905. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  43906. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  43907. return this;
  43908. };
  43909. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  43910. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  43911. return this;
  43912. };
  43913. return ArcRotateCameraInputsManager;
  43914. }(BABYLON.CameraInputsManager));
  43915. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  43916. })(BABYLON || (BABYLON = {}));
  43917. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  43918. var BABYLON;
  43919. (function (BABYLON) {
  43920. var ArcRotateCamera = /** @class */ (function (_super) {
  43921. __extends(ArcRotateCamera, _super);
  43922. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  43923. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  43924. _this.inertialAlphaOffset = 0;
  43925. _this.inertialBetaOffset = 0;
  43926. _this.inertialRadiusOffset = 0;
  43927. _this.lowerAlphaLimit = null;
  43928. _this.upperAlphaLimit = null;
  43929. _this.lowerBetaLimit = 0.01;
  43930. _this.upperBetaLimit = Math.PI;
  43931. _this.lowerRadiusLimit = null;
  43932. _this.upperRadiusLimit = null;
  43933. _this.inertialPanningX = 0;
  43934. _this.inertialPanningY = 0;
  43935. _this.pinchToPanMaxDistance = 20;
  43936. _this.panningDistanceLimit = null;
  43937. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  43938. _this.panningInertia = 0.9;
  43939. //-- end properties for backward compatibility for inputs
  43940. _this.zoomOnFactor = 1;
  43941. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  43942. _this.allowUpsideDown = true;
  43943. _this._viewMatrix = new BABYLON.Matrix();
  43944. // Panning
  43945. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  43946. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  43947. _this.checkCollisions = false;
  43948. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43949. _this._previousPosition = BABYLON.Vector3.Zero();
  43950. _this._collisionVelocity = BABYLON.Vector3.Zero();
  43951. _this._newPosition = BABYLON.Vector3.Zero();
  43952. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43953. if (collidedMesh === void 0) { collidedMesh = null; }
  43954. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  43955. newPosition.multiplyInPlace(_this._collider._radius);
  43956. }
  43957. if (!collidedMesh) {
  43958. _this._previousPosition.copyFrom(_this.position);
  43959. }
  43960. else {
  43961. _this.setPosition(newPosition);
  43962. if (_this.onCollide) {
  43963. _this.onCollide(collidedMesh);
  43964. }
  43965. }
  43966. // Recompute because of constraints
  43967. var cosa = Math.cos(_this.alpha);
  43968. var sina = Math.sin(_this.alpha);
  43969. var cosb = Math.cos(_this.beta);
  43970. var sinb = Math.sin(_this.beta);
  43971. if (sinb === 0) {
  43972. sinb = 0.0001;
  43973. }
  43974. var target = _this._getTargetPosition();
  43975. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  43976. _this.position.copyFrom(_this._newPosition);
  43977. var up = _this.upVector;
  43978. if (_this.allowUpsideDown && _this.beta < 0) {
  43979. up = up.clone();
  43980. up = up.negate();
  43981. }
  43982. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  43983. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  43984. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  43985. _this._collisionTriggered = false;
  43986. };
  43987. _this._target = BABYLON.Vector3.Zero();
  43988. if (target) {
  43989. _this.setTarget(target);
  43990. }
  43991. _this.alpha = alpha;
  43992. _this.beta = beta;
  43993. _this.radius = radius;
  43994. _this.getViewMatrix();
  43995. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  43996. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  43997. return _this;
  43998. }
  43999. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44000. get: function () {
  44001. return this._target;
  44002. },
  44003. set: function (value) {
  44004. this.setTarget(value);
  44005. },
  44006. enumerable: true,
  44007. configurable: true
  44008. });
  44009. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44010. //-- begin properties for backward compatibility for inputs
  44011. get: function () {
  44012. var pointers = this.inputs.attached["pointers"];
  44013. if (pointers)
  44014. return pointers.angularSensibilityX;
  44015. return 0;
  44016. },
  44017. set: function (value) {
  44018. var pointers = this.inputs.attached["pointers"];
  44019. if (pointers) {
  44020. pointers.angularSensibilityX = value;
  44021. }
  44022. },
  44023. enumerable: true,
  44024. configurable: true
  44025. });
  44026. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44027. get: function () {
  44028. var pointers = this.inputs.attached["pointers"];
  44029. if (pointers)
  44030. return pointers.angularSensibilityY;
  44031. return 0;
  44032. },
  44033. set: function (value) {
  44034. var pointers = this.inputs.attached["pointers"];
  44035. if (pointers) {
  44036. pointers.angularSensibilityY = value;
  44037. }
  44038. },
  44039. enumerable: true,
  44040. configurable: true
  44041. });
  44042. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44043. get: function () {
  44044. var pointers = this.inputs.attached["pointers"];
  44045. if (pointers)
  44046. return pointers.pinchPrecision;
  44047. return 0;
  44048. },
  44049. set: function (value) {
  44050. var pointers = this.inputs.attached["pointers"];
  44051. if (pointers) {
  44052. pointers.pinchPrecision = value;
  44053. }
  44054. },
  44055. enumerable: true,
  44056. configurable: true
  44057. });
  44058. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44059. get: function () {
  44060. var pointers = this.inputs.attached["pointers"];
  44061. if (pointers)
  44062. return pointers.pinchDeltaPercentage;
  44063. return 0;
  44064. },
  44065. set: function (value) {
  44066. var pointers = this.inputs.attached["pointers"];
  44067. if (pointers) {
  44068. pointers.pinchDeltaPercentage = value;
  44069. }
  44070. },
  44071. enumerable: true,
  44072. configurable: true
  44073. });
  44074. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44075. get: function () {
  44076. var pointers = this.inputs.attached["pointers"];
  44077. if (pointers)
  44078. return pointers.panningSensibility;
  44079. return 0;
  44080. },
  44081. set: function (value) {
  44082. var pointers = this.inputs.attached["pointers"];
  44083. if (pointers) {
  44084. pointers.panningSensibility = value;
  44085. }
  44086. },
  44087. enumerable: true,
  44088. configurable: true
  44089. });
  44090. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44091. get: function () {
  44092. var keyboard = this.inputs.attached["keyboard"];
  44093. if (keyboard)
  44094. return keyboard.keysUp;
  44095. return [];
  44096. },
  44097. set: function (value) {
  44098. var keyboard = this.inputs.attached["keyboard"];
  44099. if (keyboard)
  44100. keyboard.keysUp = value;
  44101. },
  44102. enumerable: true,
  44103. configurable: true
  44104. });
  44105. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44106. get: function () {
  44107. var keyboard = this.inputs.attached["keyboard"];
  44108. if (keyboard)
  44109. return keyboard.keysDown;
  44110. return [];
  44111. },
  44112. set: function (value) {
  44113. var keyboard = this.inputs.attached["keyboard"];
  44114. if (keyboard)
  44115. keyboard.keysDown = value;
  44116. },
  44117. enumerable: true,
  44118. configurable: true
  44119. });
  44120. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44121. get: function () {
  44122. var keyboard = this.inputs.attached["keyboard"];
  44123. if (keyboard)
  44124. return keyboard.keysLeft;
  44125. return [];
  44126. },
  44127. set: function (value) {
  44128. var keyboard = this.inputs.attached["keyboard"];
  44129. if (keyboard)
  44130. keyboard.keysLeft = value;
  44131. },
  44132. enumerable: true,
  44133. configurable: true
  44134. });
  44135. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44136. get: function () {
  44137. var keyboard = this.inputs.attached["keyboard"];
  44138. if (keyboard)
  44139. return keyboard.keysRight;
  44140. return [];
  44141. },
  44142. set: function (value) {
  44143. var keyboard = this.inputs.attached["keyboard"];
  44144. if (keyboard)
  44145. keyboard.keysRight = value;
  44146. },
  44147. enumerable: true,
  44148. configurable: true
  44149. });
  44150. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44151. get: function () {
  44152. var mousewheel = this.inputs.attached["mousewheel"];
  44153. if (mousewheel)
  44154. return mousewheel.wheelPrecision;
  44155. return 0;
  44156. },
  44157. set: function (value) {
  44158. var mousewheel = this.inputs.attached["mousewheel"];
  44159. if (mousewheel)
  44160. mousewheel.wheelPrecision = value;
  44161. },
  44162. enumerable: true,
  44163. configurable: true
  44164. });
  44165. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44166. get: function () {
  44167. var mousewheel = this.inputs.attached["mousewheel"];
  44168. if (mousewheel)
  44169. return mousewheel.wheelDeltaPercentage;
  44170. return 0;
  44171. },
  44172. set: function (value) {
  44173. var mousewheel = this.inputs.attached["mousewheel"];
  44174. if (mousewheel)
  44175. mousewheel.wheelDeltaPercentage = value;
  44176. },
  44177. enumerable: true,
  44178. configurable: true
  44179. });
  44180. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44181. get: function () {
  44182. return this._bouncingBehavior;
  44183. },
  44184. enumerable: true,
  44185. configurable: true
  44186. });
  44187. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44188. get: function () {
  44189. return this._bouncingBehavior != null;
  44190. },
  44191. set: function (value) {
  44192. if (value === this.useBouncingBehavior) {
  44193. return;
  44194. }
  44195. if (value) {
  44196. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44197. this.addBehavior(this._bouncingBehavior);
  44198. }
  44199. else if (this._bouncingBehavior) {
  44200. this.removeBehavior(this._bouncingBehavior);
  44201. this._bouncingBehavior = null;
  44202. }
  44203. },
  44204. enumerable: true,
  44205. configurable: true
  44206. });
  44207. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44208. get: function () {
  44209. return this._framingBehavior;
  44210. },
  44211. enumerable: true,
  44212. configurable: true
  44213. });
  44214. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44215. get: function () {
  44216. return this._framingBehavior != null;
  44217. },
  44218. set: function (value) {
  44219. if (value === this.useFramingBehavior) {
  44220. return;
  44221. }
  44222. if (value) {
  44223. this._framingBehavior = new BABYLON.FramingBehavior();
  44224. this.addBehavior(this._framingBehavior);
  44225. }
  44226. else if (this._framingBehavior) {
  44227. this.removeBehavior(this._framingBehavior);
  44228. this._framingBehavior = null;
  44229. }
  44230. },
  44231. enumerable: true,
  44232. configurable: true
  44233. });
  44234. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44235. get: function () {
  44236. return this._autoRotationBehavior;
  44237. },
  44238. enumerable: true,
  44239. configurable: true
  44240. });
  44241. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44242. get: function () {
  44243. return this._autoRotationBehavior != null;
  44244. },
  44245. set: function (value) {
  44246. if (value === this.useAutoRotationBehavior) {
  44247. return;
  44248. }
  44249. if (value) {
  44250. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44251. this.addBehavior(this._autoRotationBehavior);
  44252. }
  44253. else if (this._autoRotationBehavior) {
  44254. this.removeBehavior(this._autoRotationBehavior);
  44255. this._autoRotationBehavior = null;
  44256. }
  44257. },
  44258. enumerable: true,
  44259. configurable: true
  44260. });
  44261. // Cache
  44262. ArcRotateCamera.prototype._initCache = function () {
  44263. _super.prototype._initCache.call(this);
  44264. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44265. this._cache.alpha = undefined;
  44266. this._cache.beta = undefined;
  44267. this._cache.radius = undefined;
  44268. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44269. };
  44270. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44271. if (!ignoreParentClass) {
  44272. _super.prototype._updateCache.call(this);
  44273. }
  44274. this._cache._target.copyFrom(this._getTargetPosition());
  44275. this._cache.alpha = this.alpha;
  44276. this._cache.beta = this.beta;
  44277. this._cache.radius = this.radius;
  44278. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44279. };
  44280. ArcRotateCamera.prototype._getTargetPosition = function () {
  44281. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44282. var pos = this._targetHost.getAbsolutePosition();
  44283. if (this._targetBoundingCenter) {
  44284. pos.addToRef(this._targetBoundingCenter, this._target);
  44285. }
  44286. else {
  44287. this._target.copyFrom(pos);
  44288. }
  44289. }
  44290. var lockedTargetPosition = this._getLockedTargetPosition();
  44291. if (lockedTargetPosition) {
  44292. return lockedTargetPosition;
  44293. }
  44294. return this._target;
  44295. };
  44296. ArcRotateCamera.prototype.storeState = function () {
  44297. this._storedAlpha = this.alpha;
  44298. this._storedBeta = this.beta;
  44299. this._storedRadius = this.radius;
  44300. this._storedTarget = this._getTargetPosition().clone();
  44301. return _super.prototype.storeState.call(this);
  44302. };
  44303. /**
  44304. * Restored camera state. You must call storeState() first
  44305. */
  44306. ArcRotateCamera.prototype._restoreStateValues = function () {
  44307. if (!_super.prototype._restoreStateValues.call(this)) {
  44308. return false;
  44309. }
  44310. this.alpha = this._storedAlpha;
  44311. this.beta = this._storedBeta;
  44312. this.radius = this._storedRadius;
  44313. this.setTarget(this._storedTarget.clone());
  44314. this.inertialAlphaOffset = 0;
  44315. this.inertialBetaOffset = 0;
  44316. this.inertialRadiusOffset = 0;
  44317. this.inertialPanningX = 0;
  44318. this.inertialPanningY = 0;
  44319. return true;
  44320. };
  44321. // Synchronized
  44322. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44323. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44324. return false;
  44325. return this._cache._target.equals(this._getTargetPosition())
  44326. && this._cache.alpha === this.alpha
  44327. && this._cache.beta === this.beta
  44328. && this._cache.radius === this.radius
  44329. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44330. };
  44331. // Methods
  44332. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44333. var _this = this;
  44334. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44335. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44336. this._useCtrlForPanning = useCtrlForPanning;
  44337. this._panningMouseButton = panningMouseButton;
  44338. this.inputs.attachElement(element, noPreventDefault);
  44339. this._reset = function () {
  44340. _this.inertialAlphaOffset = 0;
  44341. _this.inertialBetaOffset = 0;
  44342. _this.inertialRadiusOffset = 0;
  44343. _this.inertialPanningX = 0;
  44344. _this.inertialPanningY = 0;
  44345. };
  44346. };
  44347. ArcRotateCamera.prototype.detachControl = function (element) {
  44348. this.inputs.detachElement(element);
  44349. if (this._reset) {
  44350. this._reset();
  44351. }
  44352. };
  44353. ArcRotateCamera.prototype._checkInputs = function () {
  44354. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44355. if (this._collisionTriggered) {
  44356. return;
  44357. }
  44358. this.inputs.checkInputs();
  44359. // Inertia
  44360. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44361. if (this.getScene().useRightHandedSystem) {
  44362. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44363. }
  44364. else {
  44365. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44366. }
  44367. this.beta += this.inertialBetaOffset;
  44368. this.radius -= this.inertialRadiusOffset;
  44369. this.inertialAlphaOffset *= this.inertia;
  44370. this.inertialBetaOffset *= this.inertia;
  44371. this.inertialRadiusOffset *= this.inertia;
  44372. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44373. this.inertialAlphaOffset = 0;
  44374. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44375. this.inertialBetaOffset = 0;
  44376. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44377. this.inertialRadiusOffset = 0;
  44378. }
  44379. // Panning inertia
  44380. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44381. if (!this._localDirection) {
  44382. this._localDirection = BABYLON.Vector3.Zero();
  44383. this._transformedDirection = BABYLON.Vector3.Zero();
  44384. }
  44385. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44386. this._localDirection.multiplyInPlace(this.panningAxis);
  44387. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44388. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44389. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44390. if (!this.panningAxis.y) {
  44391. this._transformedDirection.y = 0;
  44392. }
  44393. if (!this._targetHost) {
  44394. if (this.panningDistanceLimit) {
  44395. this._transformedDirection.addInPlace(this._target);
  44396. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44397. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44398. this._target.copyFrom(this._transformedDirection);
  44399. }
  44400. }
  44401. else {
  44402. this._target.addInPlace(this._transformedDirection);
  44403. }
  44404. }
  44405. this.inertialPanningX *= this.panningInertia;
  44406. this.inertialPanningY *= this.panningInertia;
  44407. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44408. this.inertialPanningX = 0;
  44409. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44410. this.inertialPanningY = 0;
  44411. }
  44412. // Limits
  44413. this._checkLimits();
  44414. _super.prototype._checkInputs.call(this);
  44415. };
  44416. ArcRotateCamera.prototype._checkLimits = function () {
  44417. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44418. if (this.allowUpsideDown && this.beta > Math.PI) {
  44419. this.beta = this.beta - (2 * Math.PI);
  44420. }
  44421. }
  44422. else {
  44423. if (this.beta < this.lowerBetaLimit) {
  44424. this.beta = this.lowerBetaLimit;
  44425. }
  44426. }
  44427. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44428. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44429. this.beta = this.beta + (2 * Math.PI);
  44430. }
  44431. }
  44432. else {
  44433. if (this.beta > this.upperBetaLimit) {
  44434. this.beta = this.upperBetaLimit;
  44435. }
  44436. }
  44437. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44438. this.alpha = this.lowerAlphaLimit;
  44439. }
  44440. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44441. this.alpha = this.upperAlphaLimit;
  44442. }
  44443. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44444. this.radius = this.lowerRadiusLimit;
  44445. }
  44446. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44447. this.radius = this.upperRadiusLimit;
  44448. }
  44449. };
  44450. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44451. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44452. this.radius = radiusv3.length();
  44453. if (this.radius === 0) {
  44454. this.radius = 0.0001; // Just to avoid division by zero
  44455. }
  44456. // Alpha
  44457. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44458. if (radiusv3.z < 0) {
  44459. this.alpha = 2 * Math.PI - this.alpha;
  44460. }
  44461. // Beta
  44462. this.beta = Math.acos(radiusv3.y / this.radius);
  44463. this._checkLimits();
  44464. };
  44465. ArcRotateCamera.prototype.setPosition = function (position) {
  44466. if (this.position.equals(position)) {
  44467. return;
  44468. }
  44469. this.position.copyFrom(position);
  44470. this.rebuildAnglesAndRadius();
  44471. };
  44472. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44473. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44474. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44475. if (target.getBoundingInfo) {
  44476. if (toBoundingCenter) {
  44477. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44478. }
  44479. else {
  44480. this._targetBoundingCenter = null;
  44481. }
  44482. this._targetHost = target;
  44483. this._target = this._getTargetPosition();
  44484. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44485. }
  44486. else {
  44487. var newTarget = target;
  44488. var currentTarget = this._getTargetPosition();
  44489. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44490. return;
  44491. }
  44492. this._targetHost = null;
  44493. this._target = newTarget;
  44494. this._targetBoundingCenter = null;
  44495. this.onMeshTargetChangedObservable.notifyObservers(null);
  44496. }
  44497. this.rebuildAnglesAndRadius();
  44498. };
  44499. ArcRotateCamera.prototype._getViewMatrix = function () {
  44500. // Compute
  44501. var cosa = Math.cos(this.alpha);
  44502. var sina = Math.sin(this.alpha);
  44503. var cosb = Math.cos(this.beta);
  44504. var sinb = Math.sin(this.beta);
  44505. if (sinb === 0) {
  44506. sinb = 0.0001;
  44507. }
  44508. var target = this._getTargetPosition();
  44509. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44510. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44511. if (!this._collider) {
  44512. this._collider = new BABYLON.Collider();
  44513. }
  44514. this._collider._radius = this.collisionRadius;
  44515. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44516. this._collisionTriggered = true;
  44517. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44518. }
  44519. else {
  44520. this.position.copyFrom(this._newPosition);
  44521. var up = this.upVector;
  44522. if (this.allowUpsideDown && sinb < 0) {
  44523. up = up.clone();
  44524. up = up.negate();
  44525. }
  44526. if (this.getScene().useRightHandedSystem) {
  44527. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44528. }
  44529. else {
  44530. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44531. }
  44532. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44533. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44534. }
  44535. this._currentTarget = target;
  44536. return this._viewMatrix;
  44537. };
  44538. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44539. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44540. meshes = meshes || this.getScene().meshes;
  44541. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44542. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44543. this.radius = distance * this.zoomOnFactor;
  44544. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44545. };
  44546. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44547. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44548. var meshesOrMinMaxVector;
  44549. var distance;
  44550. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44551. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44552. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44553. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44554. }
  44555. else {
  44556. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44557. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44558. distance = minMaxVectorAndDistance.distance;
  44559. }
  44560. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44561. if (!doNotUpdateMaxZ) {
  44562. this.maxZ = distance * 2;
  44563. }
  44564. };
  44565. /**
  44566. * @override
  44567. * Override Camera.createRigCamera
  44568. */
  44569. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44570. var alphaShift = 0;
  44571. switch (this.cameraRigMode) {
  44572. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44573. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44574. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44575. case BABYLON.Camera.RIG_MODE_VR:
  44576. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44577. break;
  44578. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44579. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44580. break;
  44581. }
  44582. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44583. rigCam._cameraRigParams = {};
  44584. return rigCam;
  44585. };
  44586. /**
  44587. * @override
  44588. * Override Camera._updateRigCameras
  44589. */
  44590. ArcRotateCamera.prototype._updateRigCameras = function () {
  44591. var camLeft = this._rigCameras[0];
  44592. var camRight = this._rigCameras[1];
  44593. camLeft.beta = camRight.beta = this.beta;
  44594. camLeft.radius = camRight.radius = this.radius;
  44595. switch (this.cameraRigMode) {
  44596. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44597. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44598. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44599. case BABYLON.Camera.RIG_MODE_VR:
  44600. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44601. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44602. break;
  44603. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44604. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44605. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44606. break;
  44607. }
  44608. _super.prototype._updateRigCameras.call(this);
  44609. };
  44610. ArcRotateCamera.prototype.dispose = function () {
  44611. this.inputs.clear();
  44612. _super.prototype.dispose.call(this);
  44613. };
  44614. ArcRotateCamera.prototype.getClassName = function () {
  44615. return "ArcRotateCamera";
  44616. };
  44617. __decorate([
  44618. BABYLON.serialize()
  44619. ], ArcRotateCamera.prototype, "alpha", void 0);
  44620. __decorate([
  44621. BABYLON.serialize()
  44622. ], ArcRotateCamera.prototype, "beta", void 0);
  44623. __decorate([
  44624. BABYLON.serialize()
  44625. ], ArcRotateCamera.prototype, "radius", void 0);
  44626. __decorate([
  44627. BABYLON.serializeAsVector3("target")
  44628. ], ArcRotateCamera.prototype, "_target", void 0);
  44629. __decorate([
  44630. BABYLON.serialize()
  44631. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44632. __decorate([
  44633. BABYLON.serialize()
  44634. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44635. __decorate([
  44636. BABYLON.serialize()
  44637. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44638. __decorate([
  44639. BABYLON.serialize()
  44640. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44641. __decorate([
  44642. BABYLON.serialize()
  44643. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44644. __decorate([
  44645. BABYLON.serialize()
  44646. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44647. __decorate([
  44648. BABYLON.serialize()
  44649. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44650. __decorate([
  44651. BABYLON.serialize()
  44652. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44653. __decorate([
  44654. BABYLON.serialize()
  44655. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44656. __decorate([
  44657. BABYLON.serialize()
  44658. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44659. __decorate([
  44660. BABYLON.serialize()
  44661. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44662. __decorate([
  44663. BABYLON.serialize()
  44664. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44665. __decorate([
  44666. BABYLON.serialize()
  44667. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44668. __decorate([
  44669. BABYLON.serializeAsVector3()
  44670. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44671. __decorate([
  44672. BABYLON.serialize()
  44673. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44674. __decorate([
  44675. BABYLON.serialize()
  44676. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44677. __decorate([
  44678. BABYLON.serialize()
  44679. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  44680. return ArcRotateCamera;
  44681. }(BABYLON.TargetCamera));
  44682. BABYLON.ArcRotateCamera = ArcRotateCamera;
  44683. })(BABYLON || (BABYLON = {}));
  44684. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  44685. var BABYLON;
  44686. (function (BABYLON) {
  44687. /**
  44688. * The HemisphericLight simulates the ambient environment light,
  44689. * so the passed direction is the light reflection direction, not the incoming direction.
  44690. */
  44691. var HemisphericLight = /** @class */ (function (_super) {
  44692. __extends(HemisphericLight, _super);
  44693. /**
  44694. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  44695. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  44696. * The HemisphericLight can't cast shadows.
  44697. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44698. * @param name The friendly name of the light
  44699. * @param direction The direction of the light reflection
  44700. * @param scene The scene the light belongs to
  44701. */
  44702. function HemisphericLight(name, direction, scene) {
  44703. var _this = _super.call(this, name, scene) || this;
  44704. /**
  44705. * The groundColor is the light in the opposite direction to the one specified during creation.
  44706. * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
  44707. */
  44708. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  44709. _this.direction = direction || BABYLON.Vector3.Up();
  44710. return _this;
  44711. }
  44712. HemisphericLight.prototype._buildUniformLayout = function () {
  44713. this._uniformBuffer.addUniform("vLightData", 4);
  44714. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44715. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44716. this._uniformBuffer.addUniform("vLightGround", 3);
  44717. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44718. this._uniformBuffer.addUniform("depthValues", 2);
  44719. this._uniformBuffer.create();
  44720. };
  44721. /**
  44722. * Returns the string "HemisphericLight".
  44723. * @return The class name
  44724. */
  44725. HemisphericLight.prototype.getClassName = function () {
  44726. return "HemisphericLight";
  44727. };
  44728. /**
  44729. * Sets the HemisphericLight direction towards the passed target (Vector3).
  44730. * Returns the updated direction.
  44731. * @param target The target the direction should point to
  44732. * @return The computed direction
  44733. */
  44734. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  44735. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  44736. return this.direction;
  44737. };
  44738. /**
  44739. * Returns the shadow generator associated to the light.
  44740. * @returns Always null for hemispheric lights because it does not support shadows.
  44741. */
  44742. HemisphericLight.prototype.getShadowGenerator = function () {
  44743. return null;
  44744. };
  44745. /**
  44746. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  44747. * @param effect The effect to update
  44748. * @param lightIndex The index of the light in the effect to update
  44749. * @returns The hemispheric light
  44750. */
  44751. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  44752. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  44753. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  44754. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  44755. return this;
  44756. };
  44757. /**
  44758. * @ignore internal use only.
  44759. */
  44760. HemisphericLight.prototype._getWorldMatrix = function () {
  44761. if (!this._worldMatrix) {
  44762. this._worldMatrix = BABYLON.Matrix.Identity();
  44763. }
  44764. return this._worldMatrix;
  44765. };
  44766. /**
  44767. * Returns the integer 3.
  44768. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44769. */
  44770. HemisphericLight.prototype.getTypeID = function () {
  44771. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  44772. };
  44773. __decorate([
  44774. BABYLON.serializeAsColor3()
  44775. ], HemisphericLight.prototype, "groundColor", void 0);
  44776. __decorate([
  44777. BABYLON.serializeAsVector3()
  44778. ], HemisphericLight.prototype, "direction", void 0);
  44779. return HemisphericLight;
  44780. }(BABYLON.Light));
  44781. BABYLON.HemisphericLight = HemisphericLight;
  44782. })(BABYLON || (BABYLON = {}));
  44783. //# sourceMappingURL=babylon.hemisphericLight.js.map
  44784. var BABYLON;
  44785. (function (BABYLON) {
  44786. /**
  44787. * Base implementation of @see IShadowLight
  44788. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  44789. */
  44790. var ShadowLight = /** @class */ (function (_super) {
  44791. __extends(ShadowLight, _super);
  44792. function ShadowLight() {
  44793. var _this = _super !== null && _super.apply(this, arguments) || this;
  44794. _this._needProjectionMatrixCompute = true;
  44795. return _this;
  44796. }
  44797. ShadowLight.prototype._setPosition = function (value) {
  44798. this._position = value;
  44799. };
  44800. Object.defineProperty(ShadowLight.prototype, "position", {
  44801. /**
  44802. * Sets the position the shadow will be casted from. Also use as the light position for both
  44803. * point and spot lights.
  44804. */
  44805. get: function () {
  44806. return this._position;
  44807. },
  44808. /**
  44809. * Sets the position the shadow will be casted from. Also use as the light position for both
  44810. * point and spot lights.
  44811. */
  44812. set: function (value) {
  44813. this._setPosition(value);
  44814. },
  44815. enumerable: true,
  44816. configurable: true
  44817. });
  44818. ShadowLight.prototype._setDirection = function (value) {
  44819. this._direction = value;
  44820. };
  44821. Object.defineProperty(ShadowLight.prototype, "direction", {
  44822. /**
  44823. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  44824. * Also use as the light direction on spot and directional lights.
  44825. */
  44826. get: function () {
  44827. return this._direction;
  44828. },
  44829. /**
  44830. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  44831. * Also use as the light direction on spot and directional lights.
  44832. */
  44833. set: function (value) {
  44834. this._setDirection(value);
  44835. },
  44836. enumerable: true,
  44837. configurable: true
  44838. });
  44839. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  44840. /**
  44841. * Gets the shadow projection clipping minimum z value.
  44842. */
  44843. get: function () {
  44844. return this._shadowMinZ;
  44845. },
  44846. /**
  44847. * Sets the shadow projection clipping minimum z value.
  44848. */
  44849. set: function (value) {
  44850. this._shadowMinZ = value;
  44851. this.forceProjectionMatrixCompute();
  44852. },
  44853. enumerable: true,
  44854. configurable: true
  44855. });
  44856. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  44857. /**
  44858. * Sets the shadow projection clipping maximum z value.
  44859. */
  44860. get: function () {
  44861. return this._shadowMaxZ;
  44862. },
  44863. /**
  44864. * Gets the shadow projection clipping maximum z value.
  44865. */
  44866. set: function (value) {
  44867. this._shadowMaxZ = value;
  44868. this.forceProjectionMatrixCompute();
  44869. },
  44870. enumerable: true,
  44871. configurable: true
  44872. });
  44873. /**
  44874. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  44875. * @returns true if the information has been computed, false if it does not need to (no parenting)
  44876. */
  44877. ShadowLight.prototype.computeTransformedInformation = function () {
  44878. if (this.parent && this.parent.getWorldMatrix) {
  44879. if (!this.transformedPosition) {
  44880. this.transformedPosition = BABYLON.Vector3.Zero();
  44881. }
  44882. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  44883. // In case the direction is present.
  44884. if (this.direction) {
  44885. if (!this.transformedDirection) {
  44886. this.transformedDirection = BABYLON.Vector3.Zero();
  44887. }
  44888. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  44889. }
  44890. return true;
  44891. }
  44892. return false;
  44893. };
  44894. /**
  44895. * Return the depth scale used for the shadow map.
  44896. * @returns the depth scale.
  44897. */
  44898. ShadowLight.prototype.getDepthScale = function () {
  44899. return 50.0;
  44900. };
  44901. /**
  44902. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  44903. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44904. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44905. */
  44906. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  44907. return this.transformedDirection ? this.transformedDirection : this.direction;
  44908. };
  44909. /**
  44910. * Returns the ShadowLight absolute position in the World.
  44911. * @returns the position vector in world space
  44912. */
  44913. ShadowLight.prototype.getAbsolutePosition = function () {
  44914. return this.transformedPosition ? this.transformedPosition : this.position;
  44915. };
  44916. /**
  44917. * Sets the ShadowLight direction toward the passed target.
  44918. * @param target The point tot target in local space
  44919. * @returns the updated ShadowLight direction
  44920. */
  44921. ShadowLight.prototype.setDirectionToTarget = function (target) {
  44922. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  44923. return this.direction;
  44924. };
  44925. /**
  44926. * Returns the light rotation in euler definition.
  44927. * @returns the x y z rotation in local space.
  44928. */
  44929. ShadowLight.prototype.getRotation = function () {
  44930. this.direction.normalize();
  44931. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  44932. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  44933. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  44934. };
  44935. /**
  44936. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  44937. * @returns true if a cube texture needs to be use
  44938. */
  44939. ShadowLight.prototype.needCube = function () {
  44940. return false;
  44941. };
  44942. /**
  44943. * Detects if the projection matrix requires to be recomputed this frame.
  44944. * @returns true if it requires to be recomputed otherwise, false.
  44945. */
  44946. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  44947. return this._needProjectionMatrixCompute;
  44948. };
  44949. /**
  44950. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  44951. */
  44952. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  44953. this._needProjectionMatrixCompute = true;
  44954. };
  44955. /**
  44956. * Get the world matrix of the sahdow lights.
  44957. * @ignore Internal Use Only
  44958. */
  44959. ShadowLight.prototype._getWorldMatrix = function () {
  44960. if (!this._worldMatrix) {
  44961. this._worldMatrix = BABYLON.Matrix.Identity();
  44962. }
  44963. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  44964. return this._worldMatrix;
  44965. };
  44966. /**
  44967. * Gets the minZ used for shadow according to both the scene and the light.
  44968. * @param activeCamera The camera we are returning the min for
  44969. * @returns the depth min z
  44970. */
  44971. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  44972. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  44973. };
  44974. /**
  44975. * Gets the maxZ used for shadow according to both the scene and the light.
  44976. * @param activeCamera The camera we are returning the max for
  44977. * @returns the depth max z
  44978. */
  44979. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  44980. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  44981. };
  44982. /**
  44983. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  44984. * @param matrix The materix to updated with the projection information
  44985. * @param viewMatrix The transform matrix of the light
  44986. * @param renderList The list of mesh to render in the map
  44987. * @returns The current light
  44988. */
  44989. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44990. if (this.customProjectionMatrixBuilder) {
  44991. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  44992. }
  44993. else {
  44994. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44995. }
  44996. return this;
  44997. };
  44998. __decorate([
  44999. BABYLON.serializeAsVector3()
  45000. ], ShadowLight.prototype, "position", null);
  45001. __decorate([
  45002. BABYLON.serializeAsVector3()
  45003. ], ShadowLight.prototype, "direction", null);
  45004. __decorate([
  45005. BABYLON.serialize()
  45006. ], ShadowLight.prototype, "shadowMinZ", null);
  45007. __decorate([
  45008. BABYLON.serialize()
  45009. ], ShadowLight.prototype, "shadowMaxZ", null);
  45010. return ShadowLight;
  45011. }(BABYLON.Light));
  45012. BABYLON.ShadowLight = ShadowLight;
  45013. })(BABYLON || (BABYLON = {}));
  45014. //# sourceMappingURL=babylon.shadowLight.js.map
  45015. var BABYLON;
  45016. (function (BABYLON) {
  45017. /**
  45018. * A point light is a light defined by an unique point in world space.
  45019. * The light is emitted in every direction from this point.
  45020. * A good example of a point light is a standard light bulb.
  45021. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45022. */
  45023. var PointLight = /** @class */ (function (_super) {
  45024. __extends(PointLight, _super);
  45025. /**
  45026. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45027. * A PointLight emits the light in every direction.
  45028. * It can cast shadows.
  45029. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45030. * ```javascript
  45031. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45032. * ```
  45033. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45034. * @param name The light friendly name
  45035. * @param position The position of the point light in the scene
  45036. * @param scene The scene the lights belongs to
  45037. */
  45038. function PointLight(name, position, scene) {
  45039. var _this = _super.call(this, name, scene) || this;
  45040. _this._shadowAngle = Math.PI / 2;
  45041. _this.position = position;
  45042. return _this;
  45043. }
  45044. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45045. /**
  45046. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45047. * This specifies what angle the shadow will use to be created.
  45048. *
  45049. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45050. */
  45051. get: function () {
  45052. return this._shadowAngle;
  45053. },
  45054. /**
  45055. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45056. * This specifies what angle the shadow will use to be created.
  45057. *
  45058. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45059. */
  45060. set: function (value) {
  45061. this._shadowAngle = value;
  45062. this.forceProjectionMatrixCompute();
  45063. },
  45064. enumerable: true,
  45065. configurable: true
  45066. });
  45067. Object.defineProperty(PointLight.prototype, "direction", {
  45068. /**
  45069. * Gets the direction if it has been set.
  45070. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45071. */
  45072. get: function () {
  45073. return this._direction;
  45074. },
  45075. /**
  45076. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45077. */
  45078. set: function (value) {
  45079. var previousNeedCube = this.needCube();
  45080. this._direction = value;
  45081. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45082. this._shadowGenerator.recreateShadowMap();
  45083. }
  45084. },
  45085. enumerable: true,
  45086. configurable: true
  45087. });
  45088. /**
  45089. * Returns the string "PointLight"
  45090. * @returns the class name
  45091. */
  45092. PointLight.prototype.getClassName = function () {
  45093. return "PointLight";
  45094. };
  45095. /**
  45096. * Returns the integer 0.
  45097. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45098. */
  45099. PointLight.prototype.getTypeID = function () {
  45100. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45101. };
  45102. /**
  45103. * Specifies wether or not the shadowmap should be a cube texture.
  45104. * @returns true if the shadowmap needs to be a cube texture.
  45105. */
  45106. PointLight.prototype.needCube = function () {
  45107. return !this.direction;
  45108. };
  45109. /**
  45110. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45111. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45112. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45113. */
  45114. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45115. if (this.direction) {
  45116. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45117. }
  45118. else {
  45119. switch (faceIndex) {
  45120. case 0:
  45121. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45122. case 1:
  45123. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45124. case 2:
  45125. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45126. case 3:
  45127. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45128. case 4:
  45129. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45130. case 5:
  45131. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45132. }
  45133. }
  45134. return BABYLON.Vector3.Zero();
  45135. };
  45136. /**
  45137. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45138. * - fov = PI / 2
  45139. * - aspect ratio : 1.0
  45140. * - z-near and far equal to the active camera minZ and maxZ.
  45141. * Returns the PointLight.
  45142. */
  45143. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45144. var activeCamera = this.getScene().activeCamera;
  45145. if (!activeCamera) {
  45146. return;
  45147. }
  45148. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45149. };
  45150. PointLight.prototype._buildUniformLayout = function () {
  45151. this._uniformBuffer.addUniform("vLightData", 4);
  45152. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45153. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45154. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45155. this._uniformBuffer.addUniform("depthValues", 2);
  45156. this._uniformBuffer.create();
  45157. };
  45158. /**
  45159. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45160. * @param effect The effect to update
  45161. * @param lightIndex The index of the light in the effect to update
  45162. * @returns The point light
  45163. */
  45164. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45165. if (this.computeTransformedInformation()) {
  45166. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45167. return this;
  45168. }
  45169. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45170. return this;
  45171. };
  45172. __decorate([
  45173. BABYLON.serialize()
  45174. ], PointLight.prototype, "shadowAngle", null);
  45175. return PointLight;
  45176. }(BABYLON.ShadowLight));
  45177. BABYLON.PointLight = PointLight;
  45178. })(BABYLON || (BABYLON = {}));
  45179. //# sourceMappingURL=babylon.pointLight.js.map
  45180. var BABYLON;
  45181. (function (BABYLON) {
  45182. /**
  45183. * A directional light is defined by a direction (what a surprise!).
  45184. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45185. * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
  45186. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45187. */
  45188. var DirectionalLight = /** @class */ (function (_super) {
  45189. __extends(DirectionalLight, _super);
  45190. /**
  45191. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45192. * The directional light is emitted from everywhere in the given direction.
  45193. * It can cast shawdows.
  45194. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45195. * @param name The friendly name of the light
  45196. * @param direction The direction of the light
  45197. * @param scene The scene the light belongs to
  45198. */
  45199. function DirectionalLight(name, direction, scene) {
  45200. var _this = _super.call(this, name, scene) || this;
  45201. _this._shadowFrustumSize = 0;
  45202. _this._shadowOrthoScale = 0.5;
  45203. /**
  45204. * Automatically compute the projection matrix to best fit (including all the casters)
  45205. * on each frame.
  45206. */
  45207. _this.autoUpdateExtends = true;
  45208. // Cache
  45209. _this._orthoLeft = Number.MAX_VALUE;
  45210. _this._orthoRight = Number.MIN_VALUE;
  45211. _this._orthoTop = Number.MIN_VALUE;
  45212. _this._orthoBottom = Number.MAX_VALUE;
  45213. _this.position = direction.scale(-1.0);
  45214. _this.direction = direction;
  45215. return _this;
  45216. }
  45217. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45218. /**
  45219. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45220. */
  45221. get: function () {
  45222. return this._shadowFrustumSize;
  45223. },
  45224. /**
  45225. * Specifies a fix frustum size for the shadow generation.
  45226. */
  45227. set: function (value) {
  45228. this._shadowFrustumSize = value;
  45229. this.forceProjectionMatrixCompute();
  45230. },
  45231. enumerable: true,
  45232. configurable: true
  45233. });
  45234. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45235. /**
  45236. * Gets the shadow projection scale against the optimal computed one.
  45237. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45238. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45239. */
  45240. get: function () {
  45241. return this._shadowOrthoScale;
  45242. },
  45243. /**
  45244. * Sets the shadow projection scale against the optimal computed one.
  45245. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45246. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45247. */
  45248. set: function (value) {
  45249. this._shadowOrthoScale = value;
  45250. this.forceProjectionMatrixCompute();
  45251. },
  45252. enumerable: true,
  45253. configurable: true
  45254. });
  45255. /**
  45256. * Returns the string "DirectionalLight".
  45257. * @return The class name
  45258. */
  45259. DirectionalLight.prototype.getClassName = function () {
  45260. return "DirectionalLight";
  45261. };
  45262. /**
  45263. * Returns the integer 1.
  45264. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45265. */
  45266. DirectionalLight.prototype.getTypeID = function () {
  45267. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45268. };
  45269. /**
  45270. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45271. * Returns the DirectionalLight Shadow projection matrix.
  45272. */
  45273. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45274. if (this.shadowFrustumSize > 0) {
  45275. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45276. }
  45277. else {
  45278. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45279. }
  45280. };
  45281. /**
  45282. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45283. * Returns the DirectionalLight Shadow projection matrix.
  45284. */
  45285. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45286. var activeCamera = this.getScene().activeCamera;
  45287. if (!activeCamera) {
  45288. return;
  45289. }
  45290. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45291. };
  45292. /**
  45293. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45294. * Returns the DirectionalLight Shadow projection matrix.
  45295. */
  45296. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45297. var activeCamera = this.getScene().activeCamera;
  45298. if (!activeCamera) {
  45299. return;
  45300. }
  45301. // Check extends
  45302. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45303. var tempVector3 = BABYLON.Vector3.Zero();
  45304. this._orthoLeft = Number.MAX_VALUE;
  45305. this._orthoRight = Number.MIN_VALUE;
  45306. this._orthoTop = Number.MIN_VALUE;
  45307. this._orthoBottom = Number.MAX_VALUE;
  45308. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45309. var mesh = renderList[meshIndex];
  45310. if (!mesh) {
  45311. continue;
  45312. }
  45313. var boundingInfo = mesh.getBoundingInfo();
  45314. var boundingBox = boundingInfo.boundingBox;
  45315. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45316. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45317. if (tempVector3.x < this._orthoLeft)
  45318. this._orthoLeft = tempVector3.x;
  45319. if (tempVector3.y < this._orthoBottom)
  45320. this._orthoBottom = tempVector3.y;
  45321. if (tempVector3.x > this._orthoRight)
  45322. this._orthoRight = tempVector3.x;
  45323. if (tempVector3.y > this._orthoTop)
  45324. this._orthoTop = tempVector3.y;
  45325. }
  45326. }
  45327. }
  45328. var xOffset = this._orthoRight - this._orthoLeft;
  45329. var yOffset = this._orthoTop - this._orthoBottom;
  45330. 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);
  45331. };
  45332. DirectionalLight.prototype._buildUniformLayout = function () {
  45333. this._uniformBuffer.addUniform("vLightData", 4);
  45334. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45335. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45336. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45337. this._uniformBuffer.addUniform("depthValues", 2);
  45338. this._uniformBuffer.create();
  45339. };
  45340. /**
  45341. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45342. * @param effect The effect to update
  45343. * @param lightIndex The index of the light in the effect to update
  45344. * @returns The directional light
  45345. */
  45346. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45347. if (this.computeTransformedInformation()) {
  45348. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45349. return this;
  45350. }
  45351. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45352. return this;
  45353. };
  45354. /**
  45355. * Gets the minZ used for shadow according to both the scene and the light.
  45356. *
  45357. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45358. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45359. * @param activeCamera The camera we are returning the min for
  45360. * @returns the depth min z
  45361. */
  45362. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45363. return 1;
  45364. };
  45365. /**
  45366. * Gets the maxZ used for shadow according to both the scene and the light.
  45367. *
  45368. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45369. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45370. * @param activeCamera The camera we are returning the max for
  45371. * @returns the depth max z
  45372. */
  45373. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45374. return 1;
  45375. };
  45376. __decorate([
  45377. BABYLON.serialize()
  45378. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45379. __decorate([
  45380. BABYLON.serialize()
  45381. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45382. __decorate([
  45383. BABYLON.serialize()
  45384. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45385. return DirectionalLight;
  45386. }(BABYLON.ShadowLight));
  45387. BABYLON.DirectionalLight = DirectionalLight;
  45388. })(BABYLON || (BABYLON = {}));
  45389. //# sourceMappingURL=babylon.directionalLight.js.map
  45390. var BABYLON;
  45391. (function (BABYLON) {
  45392. /**
  45393. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45394. * These values define a cone of light starting from the position, emitting toward the direction.
  45395. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45396. * and the exponent defines the speed of the decay of the light with distance (reach).
  45397. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45398. */
  45399. var SpotLight = /** @class */ (function (_super) {
  45400. __extends(SpotLight, _super);
  45401. /**
  45402. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45403. * It can cast shadows.
  45404. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45405. * @param name The light friendly name
  45406. * @param position The position of the spot light in the scene
  45407. * @param direction The direction of the light in the scene
  45408. * @param angle The cone angle of the light in Radians
  45409. * @param exponent The light decay speed with the distance from the emission spot
  45410. * @param scene The scene the lights belongs to
  45411. */
  45412. function SpotLight(name, position, direction, angle, exponent, scene) {
  45413. var _this = _super.call(this, name, scene) || this;
  45414. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45415. _this._projectionTextureLightNear = 1e-6;
  45416. _this._projectionTextureLightFar = 1000.0;
  45417. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45418. _this._projectionTextureViewLightDirty = true;
  45419. _this._projectionTextureProjectionLightDirty = true;
  45420. _this._projectionTextureDirty = true;
  45421. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45422. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45423. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45424. _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
  45425. _this.position = position;
  45426. _this.direction = direction;
  45427. _this.angle = angle;
  45428. _this.exponent = exponent;
  45429. return _this;
  45430. }
  45431. Object.defineProperty(SpotLight.prototype, "angle", {
  45432. /**
  45433. * Gets the cone angle of the spot light in Radians.
  45434. */
  45435. get: function () {
  45436. return this._angle;
  45437. },
  45438. /**
  45439. * Sets the cone angle of the spot light in Radians.
  45440. */
  45441. set: function (value) {
  45442. this._angle = value;
  45443. this._projectionTextureProjectionLightDirty = true;
  45444. this.forceProjectionMatrixCompute();
  45445. },
  45446. enumerable: true,
  45447. configurable: true
  45448. });
  45449. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45450. /**
  45451. * Allows scaling the angle of the light for shadow generation only.
  45452. */
  45453. get: function () {
  45454. return this._shadowAngleScale;
  45455. },
  45456. /**
  45457. * Allows scaling the angle of the light for shadow generation only.
  45458. */
  45459. set: function (value) {
  45460. this._shadowAngleScale = value;
  45461. this.forceProjectionMatrixCompute();
  45462. },
  45463. enumerable: true,
  45464. configurable: true
  45465. });
  45466. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45467. /**
  45468. * Allows reading the projecton texture
  45469. */
  45470. get: function () {
  45471. return this._projectionTextureMatrix;
  45472. },
  45473. enumerable: true,
  45474. configurable: true
  45475. });
  45476. ;
  45477. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45478. /**
  45479. * Gets the near clip of the Spotlight for texture projection.
  45480. */
  45481. get: function () {
  45482. return this._projectionTextureLightNear;
  45483. },
  45484. /**
  45485. * Sets the near clip of the Spotlight for texture projection.
  45486. */
  45487. set: function (value) {
  45488. this._projectionTextureLightNear = value;
  45489. this._projectionTextureProjectionLightDirty = true;
  45490. },
  45491. enumerable: true,
  45492. configurable: true
  45493. });
  45494. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45495. /**
  45496. * Gets the far clip of the Spotlight for texture projection.
  45497. */
  45498. get: function () {
  45499. return this._projectionTextureLightFar;
  45500. },
  45501. /**
  45502. * Sets the far clip of the Spotlight for texture projection.
  45503. */
  45504. set: function (value) {
  45505. this._projectionTextureLightFar = value;
  45506. this._projectionTextureProjectionLightDirty = true;
  45507. },
  45508. enumerable: true,
  45509. configurable: true
  45510. });
  45511. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45512. /**
  45513. * Gets the Up vector of the Spotlight for texture projection.
  45514. */
  45515. get: function () {
  45516. return this._projectionTextureUpDirection;
  45517. },
  45518. /**
  45519. * Sets the Up vector of the Spotlight for texture projection.
  45520. */
  45521. set: function (value) {
  45522. this._projectionTextureUpDirection = value;
  45523. this._projectionTextureProjectionLightDirty = true;
  45524. },
  45525. enumerable: true,
  45526. configurable: true
  45527. });
  45528. ;
  45529. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45530. /**
  45531. * Gets the projection texture of the light.
  45532. */
  45533. get: function () {
  45534. return this._projectionTexture;
  45535. },
  45536. /**
  45537. * Sets the projection texture of the light.
  45538. */
  45539. set: function (value) {
  45540. this._projectionTexture = value;
  45541. this._projectionTextureDirty = true;
  45542. },
  45543. enumerable: true,
  45544. configurable: true
  45545. });
  45546. /**
  45547. * Returns the string "SpotLight".
  45548. * @returns the class name
  45549. */
  45550. SpotLight.prototype.getClassName = function () {
  45551. return "SpotLight";
  45552. };
  45553. /**
  45554. * Returns the integer 2.
  45555. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45556. */
  45557. SpotLight.prototype.getTypeID = function () {
  45558. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45559. };
  45560. /**
  45561. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45562. */
  45563. SpotLight.prototype._setDirection = function (value) {
  45564. _super.prototype._setDirection.call(this, value);
  45565. this._projectionTextureViewLightDirty = true;
  45566. };
  45567. /**
  45568. * Overrides the position setter to recompute the projection texture view light Matrix.
  45569. */
  45570. SpotLight.prototype._setPosition = function (value) {
  45571. _super.prototype._setPosition.call(this, value);
  45572. this._projectionTextureViewLightDirty = true;
  45573. };
  45574. /**
  45575. * 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.
  45576. * Returns the SpotLight.
  45577. */
  45578. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45579. var activeCamera = this.getScene().activeCamera;
  45580. if (!activeCamera) {
  45581. return;
  45582. }
  45583. this._shadowAngleScale = this._shadowAngleScale || 1;
  45584. var angle = this._shadowAngleScale * this._angle;
  45585. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45586. };
  45587. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45588. this._projectionTextureViewLightDirty = false;
  45589. this._projectionTextureDirty = true;
  45590. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45591. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45592. };
  45593. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45594. this._projectionTextureProjectionLightDirty = false;
  45595. this._projectionTextureDirty = true;
  45596. var light_far = this.projectionTextureLightFar;
  45597. var light_near = this.projectionTextureLightNear;
  45598. var P = light_far / (light_far - light_near);
  45599. var Q = -P * light_near;
  45600. var S = 1.0 / Math.tan(this._angle / 2.0);
  45601. var A = 1.0;
  45602. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
  45603. };
  45604. /**
  45605. * Main function for light texture projection matrix computing.
  45606. */
  45607. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45608. this._projectionTextureDirty = false;
  45609. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45610. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45611. };
  45612. SpotLight.prototype._buildUniformLayout = function () {
  45613. this._uniformBuffer.addUniform("vLightData", 4);
  45614. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45615. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45616. this._uniformBuffer.addUniform("vLightDirection", 3);
  45617. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45618. this._uniformBuffer.addUniform("depthValues", 2);
  45619. this._uniformBuffer.create();
  45620. };
  45621. /**
  45622. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45623. * @param effect The effect to update
  45624. * @param lightIndex The index of the light in the effect to update
  45625. * @returns The spot light
  45626. */
  45627. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45628. var normalizeDirection;
  45629. if (this.computeTransformedInformation()) {
  45630. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45631. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45632. }
  45633. else {
  45634. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45635. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45636. }
  45637. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45638. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45639. if (this._projectionTextureViewLightDirty) {
  45640. this._computeProjectionTextureViewLightMatrix();
  45641. }
  45642. if (this._projectionTextureProjectionLightDirty) {
  45643. this._computeProjectionTextureProjectionLightMatrix();
  45644. }
  45645. if (this._projectionTextureDirty) {
  45646. this._computeProjectionTextureMatrix();
  45647. }
  45648. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45649. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45650. }
  45651. return this;
  45652. };
  45653. /**
  45654. * Disposes the light and the associated resources.
  45655. */
  45656. SpotLight.prototype.dispose = function () {
  45657. _super.prototype.dispose.call(this);
  45658. if (this._projectionTexture) {
  45659. this._projectionTexture.dispose();
  45660. }
  45661. };
  45662. __decorate([
  45663. BABYLON.serialize()
  45664. ], SpotLight.prototype, "angle", null);
  45665. __decorate([
  45666. BABYLON.serialize()
  45667. ], SpotLight.prototype, "shadowAngleScale", null);
  45668. __decorate([
  45669. BABYLON.serialize()
  45670. ], SpotLight.prototype, "exponent", void 0);
  45671. __decorate([
  45672. BABYLON.serialize()
  45673. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45674. __decorate([
  45675. BABYLON.serialize()
  45676. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45677. __decorate([
  45678. BABYLON.serialize()
  45679. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  45680. __decorate([
  45681. BABYLON.serializeAsTexture("projectedLightTexture")
  45682. ], SpotLight.prototype, "_projectionTexture", void 0);
  45683. return SpotLight;
  45684. }(BABYLON.ShadowLight));
  45685. BABYLON.SpotLight = SpotLight;
  45686. })(BABYLON || (BABYLON = {}));
  45687. //# sourceMappingURL=babylon.spotLight.js.map
  45688. var BABYLON;
  45689. (function (BABYLON) {
  45690. var AnimationRange = /** @class */ (function () {
  45691. function AnimationRange(name, from, to) {
  45692. this.name = name;
  45693. this.from = from;
  45694. this.to = to;
  45695. }
  45696. AnimationRange.prototype.clone = function () {
  45697. return new AnimationRange(this.name, this.from, this.to);
  45698. };
  45699. return AnimationRange;
  45700. }());
  45701. BABYLON.AnimationRange = AnimationRange;
  45702. /**
  45703. * Composed of a frame, and an action function
  45704. */
  45705. var AnimationEvent = /** @class */ (function () {
  45706. function AnimationEvent(frame, action, onlyOnce) {
  45707. this.frame = frame;
  45708. this.action = action;
  45709. this.onlyOnce = onlyOnce;
  45710. this.isDone = false;
  45711. }
  45712. return AnimationEvent;
  45713. }());
  45714. BABYLON.AnimationEvent = AnimationEvent;
  45715. var PathCursor = /** @class */ (function () {
  45716. function PathCursor(path) {
  45717. this.path = path;
  45718. this._onchange = new Array();
  45719. this.value = 0;
  45720. this.animations = new Array();
  45721. }
  45722. PathCursor.prototype.getPoint = function () {
  45723. var point = this.path.getPointAtLengthPosition(this.value);
  45724. return new BABYLON.Vector3(point.x, 0, point.y);
  45725. };
  45726. PathCursor.prototype.moveAhead = function (step) {
  45727. if (step === void 0) { step = 0.002; }
  45728. this.move(step);
  45729. return this;
  45730. };
  45731. PathCursor.prototype.moveBack = function (step) {
  45732. if (step === void 0) { step = 0.002; }
  45733. this.move(-step);
  45734. return this;
  45735. };
  45736. PathCursor.prototype.move = function (step) {
  45737. if (Math.abs(step) > 1) {
  45738. throw "step size should be less than 1.";
  45739. }
  45740. this.value += step;
  45741. this.ensureLimits();
  45742. this.raiseOnChange();
  45743. return this;
  45744. };
  45745. PathCursor.prototype.ensureLimits = function () {
  45746. while (this.value > 1) {
  45747. this.value -= 1;
  45748. }
  45749. while (this.value < 0) {
  45750. this.value += 1;
  45751. }
  45752. return this;
  45753. };
  45754. // used by animation engine
  45755. PathCursor.prototype.raiseOnChange = function () {
  45756. var _this = this;
  45757. this._onchange.forEach(function (f) { return f(_this); });
  45758. return this;
  45759. };
  45760. PathCursor.prototype.onchange = function (f) {
  45761. this._onchange.push(f);
  45762. return this;
  45763. };
  45764. return PathCursor;
  45765. }());
  45766. BABYLON.PathCursor = PathCursor;
  45767. var AnimationKeyInterpolation;
  45768. (function (AnimationKeyInterpolation) {
  45769. /**
  45770. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  45771. */
  45772. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  45773. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  45774. var Animation = /** @class */ (function () {
  45775. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  45776. this.name = name;
  45777. this.targetProperty = targetProperty;
  45778. this.framePerSecond = framePerSecond;
  45779. this.dataType = dataType;
  45780. this.loopMode = loopMode;
  45781. this.enableBlending = enableBlending;
  45782. this._runtimeAnimations = new Array();
  45783. // The set of event that will be linked to this animation
  45784. this._events = new Array();
  45785. this.blendingSpeed = 0.01;
  45786. this._ranges = {};
  45787. this.targetPropertyPath = targetProperty.split(".");
  45788. this.dataType = dataType;
  45789. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  45790. }
  45791. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  45792. var dataType = undefined;
  45793. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  45794. dataType = Animation.ANIMATIONTYPE_FLOAT;
  45795. }
  45796. else if (from instanceof BABYLON.Quaternion) {
  45797. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  45798. }
  45799. else if (from instanceof BABYLON.Vector3) {
  45800. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  45801. }
  45802. else if (from instanceof BABYLON.Vector2) {
  45803. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  45804. }
  45805. else if (from instanceof BABYLON.Color3) {
  45806. dataType = Animation.ANIMATIONTYPE_COLOR3;
  45807. }
  45808. else if (from instanceof BABYLON.Size) {
  45809. dataType = Animation.ANIMATIONTYPE_SIZE;
  45810. }
  45811. if (dataType == undefined) {
  45812. return null;
  45813. }
  45814. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  45815. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  45816. animation.setKeys(keys);
  45817. if (easingFunction !== undefined) {
  45818. animation.setEasingFunction(easingFunction);
  45819. }
  45820. return animation;
  45821. };
  45822. /**
  45823. * Sets up an animation.
  45824. * @param property the property to animate
  45825. * @param animationType the animation type to apply
  45826. * @param easingFunction the easing function used in the animation
  45827. * @returns The created animation
  45828. */
  45829. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  45830. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  45831. animation.setEasingFunction(easingFunction);
  45832. return animation;
  45833. };
  45834. /**
  45835. * Create and start an animation on a node
  45836. * @param {string} name defines the name of the global animation that will be run on all nodes
  45837. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45838. * @param {string} targetProperty defines property to animate
  45839. * @param {number} framePerSecond defines the number of frame per second yo use
  45840. * @param {number} totalFrame defines the number of frames in total
  45841. * @param {any} from defines the initial value
  45842. * @param {any} to defines the final value
  45843. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45844. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45845. * @param onAnimationEnd defines the callback to call when animation end
  45846. * @returns the animatable created for this animation
  45847. */
  45848. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45849. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45850. if (!animation) {
  45851. return null;
  45852. }
  45853. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45854. };
  45855. /**
  45856. * Create and start an animation on a node and its descendants
  45857. * @param {string} name defines the name of the global animation that will be run on all nodes
  45858. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45859. * @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.
  45860. * @param {string} targetProperty defines property to animate
  45861. * @param {number} framePerSecond defines the number of frame per second yo use
  45862. * @param {number} totalFrame defines the number of frames in total
  45863. * @param {any} from defines the initial value
  45864. * @param {any} to defines the final value
  45865. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45866. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45867. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  45868. * @returns the list of animatables created for all nodes
  45869. * @example https://www.babylonjs-playground.com/#MH0VLI
  45870. */
  45871. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45872. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45873. if (!animation) {
  45874. return null;
  45875. }
  45876. var scene = node.getScene();
  45877. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45878. };
  45879. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45880. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45881. if (!animation) {
  45882. return null;
  45883. }
  45884. node.animations.push(animation);
  45885. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45886. };
  45887. /**
  45888. * Transition property of the Camera to the target Value.
  45889. * @param property The property to transition
  45890. * @param targetValue The target Value of the property
  45891. * @param host The object where the property to animate belongs
  45892. * @param scene Scene used to run the animation
  45893. * @param frameRate Framerate (in frame/s) to use
  45894. * @param transition The transition type we want to use
  45895. * @param duration The duration of the animation, in milliseconds
  45896. * @param onAnimationEnd Call back trigger at the end of the animation.
  45897. */
  45898. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  45899. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  45900. if (duration <= 0) {
  45901. host[property] = targetValue;
  45902. if (onAnimationEnd) {
  45903. onAnimationEnd();
  45904. }
  45905. return null;
  45906. }
  45907. var endFrame = frameRate * (duration / 1000);
  45908. transition.setKeys([{
  45909. frame: 0,
  45910. value: host[property].clone ? host[property].clone() : host[property]
  45911. },
  45912. {
  45913. frame: endFrame,
  45914. value: targetValue
  45915. }]);
  45916. if (!host.animations) {
  45917. host.animations = [];
  45918. }
  45919. host.animations.push(transition);
  45920. var animation = scene.beginAnimation(host, 0, endFrame, false);
  45921. animation.onAnimationEnd = onAnimationEnd;
  45922. return animation;
  45923. };
  45924. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  45925. /**
  45926. * Return the array of runtime animations currently using this animation
  45927. */
  45928. get: function () {
  45929. return this._runtimeAnimations;
  45930. },
  45931. enumerable: true,
  45932. configurable: true
  45933. });
  45934. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  45935. get: function () {
  45936. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  45937. var runtimeAnimation = _a[_i];
  45938. if (!runtimeAnimation.isStopped) {
  45939. return true;
  45940. }
  45941. }
  45942. return false;
  45943. },
  45944. enumerable: true,
  45945. configurable: true
  45946. });
  45947. // Methods
  45948. /**
  45949. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  45950. */
  45951. Animation.prototype.toString = function (fullDetails) {
  45952. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  45953. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  45954. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  45955. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  45956. if (fullDetails) {
  45957. ret += ", Ranges: {";
  45958. var first = true;
  45959. for (var name in this._ranges) {
  45960. if (first) {
  45961. ret += ", ";
  45962. first = false;
  45963. }
  45964. ret += name;
  45965. }
  45966. ret += "}";
  45967. }
  45968. return ret;
  45969. };
  45970. /**
  45971. * Add an event to this animation.
  45972. */
  45973. Animation.prototype.addEvent = function (event) {
  45974. this._events.push(event);
  45975. };
  45976. /**
  45977. * Remove all events found at the given frame
  45978. * @param frame
  45979. */
  45980. Animation.prototype.removeEvents = function (frame) {
  45981. for (var index = 0; index < this._events.length; index++) {
  45982. if (this._events[index].frame === frame) {
  45983. this._events.splice(index, 1);
  45984. index--;
  45985. }
  45986. }
  45987. };
  45988. Animation.prototype.getEvents = function () {
  45989. return this._events;
  45990. };
  45991. Animation.prototype.createRange = function (name, from, to) {
  45992. // check name not already in use; could happen for bones after serialized
  45993. if (!this._ranges[name]) {
  45994. this._ranges[name] = new AnimationRange(name, from, to);
  45995. }
  45996. };
  45997. Animation.prototype.deleteRange = function (name, deleteFrames) {
  45998. if (deleteFrames === void 0) { deleteFrames = true; }
  45999. var range = this._ranges[name];
  46000. if (!range) {
  46001. return;
  46002. }
  46003. if (deleteFrames) {
  46004. var from = range.from;
  46005. var to = range.to;
  46006. // this loop MUST go high to low for multiple splices to work
  46007. for (var key = this._keys.length - 1; key >= 0; key--) {
  46008. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46009. this._keys.splice(key, 1);
  46010. }
  46011. }
  46012. }
  46013. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46014. };
  46015. Animation.prototype.getRange = function (name) {
  46016. return this._ranges[name];
  46017. };
  46018. Animation.prototype.getKeys = function () {
  46019. return this._keys;
  46020. };
  46021. Animation.prototype.getHighestFrame = function () {
  46022. var ret = 0;
  46023. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46024. if (ret < this._keys[key].frame) {
  46025. ret = this._keys[key].frame;
  46026. }
  46027. }
  46028. return ret;
  46029. };
  46030. Animation.prototype.getEasingFunction = function () {
  46031. return this._easingFunction;
  46032. };
  46033. Animation.prototype.setEasingFunction = function (easingFunction) {
  46034. this._easingFunction = easingFunction;
  46035. };
  46036. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46037. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46038. };
  46039. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46040. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46041. };
  46042. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46043. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46044. };
  46045. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46046. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46047. };
  46048. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46049. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46050. };
  46051. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46052. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46053. };
  46054. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46055. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46056. };
  46057. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46058. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46059. };
  46060. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46061. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46062. };
  46063. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46064. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46065. };
  46066. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46067. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46068. };
  46069. Animation.prototype.clone = function () {
  46070. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46071. clone.enableBlending = this.enableBlending;
  46072. clone.blendingSpeed = this.blendingSpeed;
  46073. if (this._keys) {
  46074. clone.setKeys(this._keys);
  46075. }
  46076. if (this._ranges) {
  46077. clone._ranges = {};
  46078. for (var name in this._ranges) {
  46079. var range = this._ranges[name];
  46080. if (!range) {
  46081. continue;
  46082. }
  46083. clone._ranges[name] = range.clone();
  46084. }
  46085. }
  46086. return clone;
  46087. };
  46088. Animation.prototype.setKeys = function (values) {
  46089. this._keys = values.slice(0);
  46090. };
  46091. Animation.prototype.serialize = function () {
  46092. var serializationObject = {};
  46093. serializationObject.name = this.name;
  46094. serializationObject.property = this.targetProperty;
  46095. serializationObject.framePerSecond = this.framePerSecond;
  46096. serializationObject.dataType = this.dataType;
  46097. serializationObject.loopBehavior = this.loopMode;
  46098. serializationObject.enableBlending = this.enableBlending;
  46099. serializationObject.blendingSpeed = this.blendingSpeed;
  46100. var dataType = this.dataType;
  46101. serializationObject.keys = [];
  46102. var keys = this.getKeys();
  46103. for (var index = 0; index < keys.length; index++) {
  46104. var animationKey = keys[index];
  46105. var key = {};
  46106. key.frame = animationKey.frame;
  46107. switch (dataType) {
  46108. case Animation.ANIMATIONTYPE_FLOAT:
  46109. key.values = [animationKey.value];
  46110. break;
  46111. case Animation.ANIMATIONTYPE_QUATERNION:
  46112. case Animation.ANIMATIONTYPE_MATRIX:
  46113. case Animation.ANIMATIONTYPE_VECTOR3:
  46114. case Animation.ANIMATIONTYPE_COLOR3:
  46115. key.values = animationKey.value.asArray();
  46116. break;
  46117. }
  46118. serializationObject.keys.push(key);
  46119. }
  46120. serializationObject.ranges = [];
  46121. for (var name in this._ranges) {
  46122. var source = this._ranges[name];
  46123. if (!source) {
  46124. continue;
  46125. }
  46126. var range = {};
  46127. range.name = name;
  46128. range.from = source.from;
  46129. range.to = source.to;
  46130. serializationObject.ranges.push(range);
  46131. }
  46132. return serializationObject;
  46133. };
  46134. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46135. get: function () {
  46136. return Animation._ANIMATIONTYPE_FLOAT;
  46137. },
  46138. enumerable: true,
  46139. configurable: true
  46140. });
  46141. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46142. get: function () {
  46143. return Animation._ANIMATIONTYPE_VECTOR3;
  46144. },
  46145. enumerable: true,
  46146. configurable: true
  46147. });
  46148. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46149. get: function () {
  46150. return Animation._ANIMATIONTYPE_VECTOR2;
  46151. },
  46152. enumerable: true,
  46153. configurable: true
  46154. });
  46155. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46156. get: function () {
  46157. return Animation._ANIMATIONTYPE_SIZE;
  46158. },
  46159. enumerable: true,
  46160. configurable: true
  46161. });
  46162. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46163. get: function () {
  46164. return Animation._ANIMATIONTYPE_QUATERNION;
  46165. },
  46166. enumerable: true,
  46167. configurable: true
  46168. });
  46169. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46170. get: function () {
  46171. return Animation._ANIMATIONTYPE_MATRIX;
  46172. },
  46173. enumerable: true,
  46174. configurable: true
  46175. });
  46176. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46177. get: function () {
  46178. return Animation._ANIMATIONTYPE_COLOR3;
  46179. },
  46180. enumerable: true,
  46181. configurable: true
  46182. });
  46183. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46184. get: function () {
  46185. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46186. },
  46187. enumerable: true,
  46188. configurable: true
  46189. });
  46190. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46191. get: function () {
  46192. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46193. },
  46194. enumerable: true,
  46195. configurable: true
  46196. });
  46197. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46198. get: function () {
  46199. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46200. },
  46201. enumerable: true,
  46202. configurable: true
  46203. });
  46204. Animation.Parse = function (parsedAnimation) {
  46205. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46206. var dataType = parsedAnimation.dataType;
  46207. var keys = [];
  46208. var data;
  46209. var index;
  46210. if (parsedAnimation.enableBlending) {
  46211. animation.enableBlending = parsedAnimation.enableBlending;
  46212. }
  46213. if (parsedAnimation.blendingSpeed) {
  46214. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46215. }
  46216. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46217. var key = parsedAnimation.keys[index];
  46218. var inTangent;
  46219. var outTangent;
  46220. switch (dataType) {
  46221. case Animation.ANIMATIONTYPE_FLOAT:
  46222. data = key.values[0];
  46223. if (key.values.length >= 1) {
  46224. inTangent = key.values[1];
  46225. }
  46226. if (key.values.length >= 2) {
  46227. outTangent = key.values[2];
  46228. }
  46229. break;
  46230. case Animation.ANIMATIONTYPE_QUATERNION:
  46231. data = BABYLON.Quaternion.FromArray(key.values);
  46232. if (key.values.length >= 8) {
  46233. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46234. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46235. inTangent = _inTangent;
  46236. }
  46237. }
  46238. if (key.values.length >= 12) {
  46239. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46240. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46241. outTangent = _outTangent;
  46242. }
  46243. }
  46244. break;
  46245. case Animation.ANIMATIONTYPE_MATRIX:
  46246. data = BABYLON.Matrix.FromArray(key.values);
  46247. break;
  46248. case Animation.ANIMATIONTYPE_COLOR3:
  46249. data = BABYLON.Color3.FromArray(key.values);
  46250. break;
  46251. case Animation.ANIMATIONTYPE_VECTOR3:
  46252. default:
  46253. data = BABYLON.Vector3.FromArray(key.values);
  46254. break;
  46255. }
  46256. var keyData = {};
  46257. keyData.frame = key.frame;
  46258. keyData.value = data;
  46259. if (inTangent != undefined) {
  46260. keyData.inTangent = inTangent;
  46261. }
  46262. if (outTangent != undefined) {
  46263. keyData.outTangent = outTangent;
  46264. }
  46265. keys.push(keyData);
  46266. }
  46267. animation.setKeys(keys);
  46268. if (parsedAnimation.ranges) {
  46269. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46270. data = parsedAnimation.ranges[index];
  46271. animation.createRange(data.name, data.from, data.to);
  46272. }
  46273. }
  46274. return animation;
  46275. };
  46276. Animation.AppendSerializedAnimations = function (source, destination) {
  46277. if (source.animations) {
  46278. destination.animations = [];
  46279. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46280. var animation = source.animations[animationIndex];
  46281. destination.animations.push(animation.serialize());
  46282. }
  46283. }
  46284. };
  46285. Animation.AllowMatricesInterpolation = false;
  46286. // Statics
  46287. Animation._ANIMATIONTYPE_FLOAT = 0;
  46288. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46289. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46290. Animation._ANIMATIONTYPE_MATRIX = 3;
  46291. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46292. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46293. Animation._ANIMATIONTYPE_SIZE = 6;
  46294. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46295. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46296. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46297. return Animation;
  46298. }());
  46299. BABYLON.Animation = Animation;
  46300. })(BABYLON || (BABYLON = {}));
  46301. //# sourceMappingURL=babylon.animation.js.map
  46302. var BABYLON;
  46303. (function (BABYLON) {
  46304. /**
  46305. * This class defines the direct association between an animation and a target
  46306. */
  46307. var TargetedAnimation = /** @class */ (function () {
  46308. function TargetedAnimation() {
  46309. }
  46310. return TargetedAnimation;
  46311. }());
  46312. BABYLON.TargetedAnimation = TargetedAnimation;
  46313. /**
  46314. * Use this class to create coordinated animations on multiple targets
  46315. */
  46316. var AnimationGroup = /** @class */ (function () {
  46317. function AnimationGroup(name, scene) {
  46318. if (scene === void 0) { scene = null; }
  46319. this.name = name;
  46320. this._targetedAnimations = new Array();
  46321. this._animatables = new Array();
  46322. this._from = Number.MAX_VALUE;
  46323. this._to = -Number.MAX_VALUE;
  46324. this._speedRatio = 1;
  46325. this.onAnimationEndObservable = new BABYLON.Observable();
  46326. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46327. this._scene.animationGroups.push(this);
  46328. }
  46329. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46330. /**
  46331. * Define if the animations are started
  46332. */
  46333. get: function () {
  46334. return this._isStarted;
  46335. },
  46336. enumerable: true,
  46337. configurable: true
  46338. });
  46339. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46340. /**
  46341. * Gets or sets the speed ratio to use for all animations
  46342. */
  46343. get: function () {
  46344. return this._speedRatio;
  46345. },
  46346. /**
  46347. * Gets or sets the speed ratio to use for all animations
  46348. */
  46349. set: function (value) {
  46350. if (this._speedRatio === value) {
  46351. return;
  46352. }
  46353. this._speedRatio = value;
  46354. for (var index = 0; index < this._animatables.length; index++) {
  46355. var animatable = this._animatables[index];
  46356. animatable.speedRatio = this._speedRatio;
  46357. }
  46358. },
  46359. enumerable: true,
  46360. configurable: true
  46361. });
  46362. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46363. /**
  46364. * Gets the targeted animations for this animation group
  46365. */
  46366. get: function () {
  46367. return this._targetedAnimations;
  46368. },
  46369. enumerable: true,
  46370. configurable: true
  46371. });
  46372. /**
  46373. * Add an animation (with its target) in the group
  46374. * @param animation defines the animation we want to add
  46375. * @param target defines the target of the animation
  46376. * @returns the {BABYLON.TargetedAnimation} object
  46377. */
  46378. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46379. var targetedAnimation = {
  46380. animation: animation,
  46381. target: target
  46382. };
  46383. var keys = animation.getKeys();
  46384. if (this._from > keys[0].frame) {
  46385. this._from = keys[0].frame;
  46386. }
  46387. if (this._to < keys[keys.length - 1].frame) {
  46388. this._to = keys[keys.length - 1].frame;
  46389. }
  46390. this._targetedAnimations.push(targetedAnimation);
  46391. return targetedAnimation;
  46392. };
  46393. /**
  46394. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46395. * It can add constant keys at begin or end
  46396. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46397. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46398. */
  46399. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46400. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46401. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46402. beginFrame = Math.max(beginFrame, this._from);
  46403. endFrame = Math.min(endFrame, this._to);
  46404. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46405. var targetedAnimation = this._targetedAnimations[index];
  46406. var keys = targetedAnimation.animation.getKeys();
  46407. var startKey = keys[0];
  46408. var endKey = keys[keys.length - 1];
  46409. if (startKey.frame > beginFrame) {
  46410. var newKey = {
  46411. frame: beginFrame,
  46412. value: startKey.value,
  46413. inTangent: startKey.inTangent,
  46414. outTangent: startKey.outTangent,
  46415. interpolation: startKey.interpolation
  46416. };
  46417. keys.splice(0, 0, newKey);
  46418. }
  46419. if (endKey.frame < endFrame) {
  46420. var newKey = {
  46421. frame: endFrame,
  46422. value: endKey.value,
  46423. inTangent: endKey.outTangent,
  46424. outTangent: endKey.outTangent,
  46425. interpolation: endKey.interpolation
  46426. };
  46427. keys.push(newKey);
  46428. }
  46429. }
  46430. return this;
  46431. };
  46432. /**
  46433. * Start all animations on given targets
  46434. * @param loop defines if animations must loop
  46435. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46436. */
  46437. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46438. var _this = this;
  46439. if (loop === void 0) { loop = false; }
  46440. if (speedRatio === void 0) { speedRatio = 1; }
  46441. if (this._isStarted || this._targetedAnimations.length === 0) {
  46442. return this;
  46443. }
  46444. var _loop_1 = function () {
  46445. var targetedAnimation = this_1._targetedAnimations[index];
  46446. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46447. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46448. }));
  46449. };
  46450. var this_1 = this;
  46451. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46452. _loop_1();
  46453. }
  46454. this._speedRatio = speedRatio;
  46455. this._isStarted = true;
  46456. return this;
  46457. };
  46458. /**
  46459. * Pause all animations
  46460. */
  46461. AnimationGroup.prototype.pause = function () {
  46462. if (!this._isStarted) {
  46463. return this;
  46464. }
  46465. for (var index = 0; index < this._animatables.length; index++) {
  46466. var animatable = this._animatables[index];
  46467. animatable.pause();
  46468. }
  46469. return this;
  46470. };
  46471. /**
  46472. * Play all animations to initial state
  46473. * This function will start() the animations if they were not started or will restart() them if they were paused
  46474. * @param loop defines if animations must loop
  46475. */
  46476. AnimationGroup.prototype.play = function (loop) {
  46477. if (this.isStarted) {
  46478. if (loop !== undefined) {
  46479. for (var index = 0; index < this._animatables.length; index++) {
  46480. var animatable = this._animatables[index];
  46481. animatable.loopAnimation = loop;
  46482. }
  46483. }
  46484. this.restart();
  46485. }
  46486. else {
  46487. this.start(loop, this._speedRatio);
  46488. }
  46489. return this;
  46490. };
  46491. /**
  46492. * Reset all animations to initial state
  46493. */
  46494. AnimationGroup.prototype.reset = function () {
  46495. if (!this._isStarted) {
  46496. return this;
  46497. }
  46498. for (var index = 0; index < this._animatables.length; index++) {
  46499. var animatable = this._animatables[index];
  46500. animatable.reset();
  46501. }
  46502. return this;
  46503. };
  46504. /**
  46505. * Restart animations from key 0
  46506. */
  46507. AnimationGroup.prototype.restart = function () {
  46508. if (!this._isStarted) {
  46509. return this;
  46510. }
  46511. for (var index = 0; index < this._animatables.length; index++) {
  46512. var animatable = this._animatables[index];
  46513. animatable.restart();
  46514. }
  46515. return this;
  46516. };
  46517. /**
  46518. * Stop all animations
  46519. */
  46520. AnimationGroup.prototype.stop = function () {
  46521. if (!this._isStarted) {
  46522. return this;
  46523. }
  46524. for (var index = 0; index < this._animatables.length; index++) {
  46525. var animatable = this._animatables[index];
  46526. animatable.stop();
  46527. }
  46528. this._isStarted = false;
  46529. return this;
  46530. };
  46531. /**
  46532. * Dispose all associated resources
  46533. */
  46534. AnimationGroup.prototype.dispose = function () {
  46535. this._targetedAnimations = [];
  46536. this._animatables = [];
  46537. var index = this._scene.animationGroups.indexOf(this);
  46538. if (index > -1) {
  46539. this._scene.animationGroups.splice(index, 1);
  46540. }
  46541. };
  46542. return AnimationGroup;
  46543. }());
  46544. BABYLON.AnimationGroup = AnimationGroup;
  46545. })(BABYLON || (BABYLON = {}));
  46546. //# sourceMappingURL=babylon.animationGroup.js.map
  46547. var BABYLON;
  46548. (function (BABYLON) {
  46549. var RuntimeAnimation = /** @class */ (function () {
  46550. function RuntimeAnimation(target, animation) {
  46551. this._offsetsCache = {};
  46552. this._highLimitsCache = {};
  46553. this._stopped = false;
  46554. this._blendingFactor = 0;
  46555. this._ratioOffset = 0;
  46556. this._animation = animation;
  46557. this._target = target;
  46558. animation._runtimeAnimations.push(this);
  46559. }
  46560. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46561. get: function () {
  46562. return this._animation;
  46563. },
  46564. enumerable: true,
  46565. configurable: true
  46566. });
  46567. RuntimeAnimation.prototype.reset = function () {
  46568. this._offsetsCache = {};
  46569. this._highLimitsCache = {};
  46570. this.currentFrame = 0;
  46571. this._blendingFactor = 0;
  46572. this._originalBlendValue = null;
  46573. };
  46574. RuntimeAnimation.prototype.isStopped = function () {
  46575. return this._stopped;
  46576. };
  46577. RuntimeAnimation.prototype.dispose = function () {
  46578. var index = this._animation.runtimeAnimations.indexOf(this);
  46579. if (index > -1) {
  46580. this._animation.runtimeAnimations.splice(index, 1);
  46581. }
  46582. };
  46583. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46584. if (typeof value === "function") {
  46585. return value();
  46586. }
  46587. return value;
  46588. };
  46589. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46590. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46591. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46592. }
  46593. this.currentFrame = currentFrame;
  46594. var keys = this._animation.getKeys();
  46595. // Try to get a hash to find the right key
  46596. 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));
  46597. if (keys[startKeyIndex].frame >= currentFrame) {
  46598. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46599. startKeyIndex--;
  46600. }
  46601. }
  46602. for (var key = startKeyIndex; key < keys.length; key++) {
  46603. var endKey = keys[key + 1];
  46604. if (endKey.frame >= currentFrame) {
  46605. var startKey = keys[key];
  46606. var startValue = this._getKeyValue(startKey.value);
  46607. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46608. return startValue;
  46609. }
  46610. var endValue = this._getKeyValue(endKey.value);
  46611. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46612. var frameDelta = endKey.frame - startKey.frame;
  46613. // gradient : percent of currentFrame between the frame inf and the frame sup
  46614. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46615. // check for easingFunction and correction of gradient
  46616. var easingFunction = this._animation.getEasingFunction();
  46617. if (easingFunction != null) {
  46618. gradient = easingFunction.ease(gradient);
  46619. }
  46620. switch (this._animation.dataType) {
  46621. // Float
  46622. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46623. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46624. switch (loopMode) {
  46625. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46626. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46627. return floatValue;
  46628. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46629. return offsetValue * repeatCount + floatValue;
  46630. }
  46631. break;
  46632. // Quaternion
  46633. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46634. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46635. switch (loopMode) {
  46636. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46637. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46638. return quatValue;
  46639. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46640. return quatValue.add(offsetValue.scale(repeatCount));
  46641. }
  46642. return quatValue;
  46643. // Vector3
  46644. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46645. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46646. switch (loopMode) {
  46647. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46648. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46649. return vec3Value;
  46650. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46651. return vec3Value.add(offsetValue.scale(repeatCount));
  46652. }
  46653. // Vector2
  46654. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46655. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46656. switch (loopMode) {
  46657. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46658. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46659. return vec2Value;
  46660. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46661. return vec2Value.add(offsetValue.scale(repeatCount));
  46662. }
  46663. // Size
  46664. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46665. switch (loopMode) {
  46666. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46667. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46668. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46669. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46670. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46671. }
  46672. // Color3
  46673. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46674. switch (loopMode) {
  46675. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46676. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46677. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46678. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46679. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46680. }
  46681. // Matrix
  46682. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  46683. switch (loopMode) {
  46684. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46685. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46686. if (BABYLON.Animation.AllowMatricesInterpolation) {
  46687. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  46688. }
  46689. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46690. return startValue;
  46691. }
  46692. default:
  46693. break;
  46694. }
  46695. break;
  46696. }
  46697. }
  46698. return this._getKeyValue(keys[keys.length - 1].value);
  46699. };
  46700. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  46701. if (blend === void 0) { blend = false; }
  46702. // Set value
  46703. var path;
  46704. var destination;
  46705. var targetPropertyPath = this._animation.targetPropertyPath;
  46706. if (targetPropertyPath.length > 1) {
  46707. var property = this._target[targetPropertyPath[0]];
  46708. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  46709. property = property[targetPropertyPath[index]];
  46710. }
  46711. path = targetPropertyPath[targetPropertyPath.length - 1];
  46712. destination = property;
  46713. }
  46714. else {
  46715. path = targetPropertyPath[0];
  46716. destination = this._target;
  46717. }
  46718. // Blending
  46719. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  46720. if (!this._originalBlendValue) {
  46721. if (destination[path].clone) {
  46722. this._originalBlendValue = destination[path].clone();
  46723. }
  46724. else {
  46725. this._originalBlendValue = destination[path];
  46726. }
  46727. }
  46728. if (this._originalBlendValue.prototype) {
  46729. if (this._originalBlendValue.prototype.Lerp) {
  46730. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  46731. }
  46732. else {
  46733. destination[path] = currentValue;
  46734. }
  46735. }
  46736. else if (this._originalBlendValue.m) {
  46737. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  46738. }
  46739. else {
  46740. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  46741. }
  46742. this._blendingFactor += this._animation.blendingSpeed;
  46743. }
  46744. else {
  46745. destination[path] = currentValue;
  46746. }
  46747. if (this._target.markAsDirty) {
  46748. this._target.markAsDirty(this._animation.targetProperty);
  46749. }
  46750. };
  46751. RuntimeAnimation.prototype.goToFrame = function (frame) {
  46752. var keys = this._animation.getKeys();
  46753. if (frame < keys[0].frame) {
  46754. frame = keys[0].frame;
  46755. }
  46756. else if (frame > keys[keys.length - 1].frame) {
  46757. frame = keys[keys.length - 1].frame;
  46758. }
  46759. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  46760. this.setValue(currentValue);
  46761. };
  46762. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  46763. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  46764. this._ratioOffset = this._previousRatio - newRatio;
  46765. };
  46766. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  46767. if (blend === void 0) { blend = false; }
  46768. var targetPropertyPath = this._animation.targetPropertyPath;
  46769. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  46770. this._stopped = true;
  46771. return false;
  46772. }
  46773. var returnValue = true;
  46774. var keys = this._animation.getKeys();
  46775. // Adding a start key at frame 0 if missing
  46776. if (keys[0].frame !== 0) {
  46777. var newKey = { frame: 0, value: keys[0].value };
  46778. keys.splice(0, 0, newKey);
  46779. }
  46780. // Check limits
  46781. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  46782. from = keys[0].frame;
  46783. }
  46784. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  46785. to = keys[keys.length - 1].frame;
  46786. }
  46787. //to and from cannot be the same key
  46788. if (from === to) {
  46789. if (from > keys[0].frame) {
  46790. from--;
  46791. }
  46792. else if (to < keys[keys.length - 1].frame) {
  46793. to++;
  46794. }
  46795. }
  46796. // Compute ratio
  46797. var range = to - from;
  46798. var offsetValue;
  46799. // ratio represents the frame delta between from and to
  46800. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  46801. var highLimitValue = 0;
  46802. this._previousDelay = delay;
  46803. this._previousRatio = ratio;
  46804. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  46805. returnValue = false;
  46806. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  46807. }
  46808. else {
  46809. // Get max value if required
  46810. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  46811. var keyOffset = to.toString() + from.toString();
  46812. if (!this._offsetsCache[keyOffset]) {
  46813. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46814. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46815. switch (this._animation.dataType) {
  46816. // Float
  46817. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46818. this._offsetsCache[keyOffset] = toValue - fromValue;
  46819. break;
  46820. // Quaternion
  46821. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46822. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46823. break;
  46824. // Vector3
  46825. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46826. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46827. // Vector2
  46828. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46829. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46830. // Size
  46831. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46832. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46833. // Color3
  46834. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46835. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46836. default:
  46837. break;
  46838. }
  46839. this._highLimitsCache[keyOffset] = toValue;
  46840. }
  46841. highLimitValue = this._highLimitsCache[keyOffset];
  46842. offsetValue = this._offsetsCache[keyOffset];
  46843. }
  46844. }
  46845. if (offsetValue === undefined) {
  46846. switch (this._animation.dataType) {
  46847. // Float
  46848. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46849. offsetValue = 0;
  46850. break;
  46851. // Quaternion
  46852. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46853. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  46854. break;
  46855. // Vector3
  46856. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46857. offsetValue = BABYLON.Vector3.Zero();
  46858. break;
  46859. // Vector2
  46860. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46861. offsetValue = BABYLON.Vector2.Zero();
  46862. break;
  46863. // Size
  46864. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46865. offsetValue = BABYLON.Size.Zero();
  46866. break;
  46867. // Color3
  46868. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46869. offsetValue = BABYLON.Color3.Black();
  46870. }
  46871. }
  46872. // Compute value
  46873. var repeatCount = (ratio / range) >> 0;
  46874. var currentFrame = returnValue ? from + ratio % range : to;
  46875. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  46876. // Set value
  46877. this.setValue(currentValue);
  46878. // Check events
  46879. var events = this._animation.getEvents();
  46880. for (var index = 0; index < events.length; index++) {
  46881. // Make sure current frame has passed event frame and that event frame is within the current range
  46882. // Also, handle both forward and reverse animations
  46883. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  46884. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  46885. var event = events[index];
  46886. if (!event.isDone) {
  46887. // If event should be done only once, remove it.
  46888. if (event.onlyOnce) {
  46889. events.splice(index, 1);
  46890. index--;
  46891. }
  46892. event.isDone = true;
  46893. event.action();
  46894. } // Don't do anything if the event has already be done.
  46895. }
  46896. else if (events[index].isDone && !events[index].onlyOnce) {
  46897. // reset event, the animation is looping
  46898. events[index].isDone = false;
  46899. }
  46900. }
  46901. if (!returnValue) {
  46902. this._stopped = true;
  46903. }
  46904. return returnValue;
  46905. };
  46906. return RuntimeAnimation;
  46907. }());
  46908. BABYLON.RuntimeAnimation = RuntimeAnimation;
  46909. })(BABYLON || (BABYLON = {}));
  46910. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  46911. var BABYLON;
  46912. (function (BABYLON) {
  46913. var Animatable = /** @class */ (function () {
  46914. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  46915. if (fromFrame === void 0) { fromFrame = 0; }
  46916. if (toFrame === void 0) { toFrame = 100; }
  46917. if (loopAnimation === void 0) { loopAnimation = false; }
  46918. if (speedRatio === void 0) { speedRatio = 1.0; }
  46919. this.target = target;
  46920. this.fromFrame = fromFrame;
  46921. this.toFrame = toFrame;
  46922. this.loopAnimation = loopAnimation;
  46923. this.onAnimationEnd = onAnimationEnd;
  46924. this._localDelayOffset = null;
  46925. this._pausedDelay = null;
  46926. this._runtimeAnimations = new Array();
  46927. this._paused = false;
  46928. this._speedRatio = 1;
  46929. this.animationStarted = false;
  46930. if (animations) {
  46931. this.appendAnimations(target, animations);
  46932. }
  46933. this._speedRatio = speedRatio;
  46934. this._scene = scene;
  46935. scene._activeAnimatables.push(this);
  46936. }
  46937. Object.defineProperty(Animatable.prototype, "speedRatio", {
  46938. get: function () {
  46939. return this._speedRatio;
  46940. },
  46941. set: function (value) {
  46942. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  46943. var animation = this._runtimeAnimations[index];
  46944. animation._prepareForSpeedRatioChange(value);
  46945. }
  46946. this._speedRatio = value;
  46947. },
  46948. enumerable: true,
  46949. configurable: true
  46950. });
  46951. // Methods
  46952. Animatable.prototype.getAnimations = function () {
  46953. return this._runtimeAnimations;
  46954. };
  46955. Animatable.prototype.appendAnimations = function (target, animations) {
  46956. for (var index = 0; index < animations.length; index++) {
  46957. var animation = animations[index];
  46958. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  46959. }
  46960. };
  46961. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  46962. var runtimeAnimations = this._runtimeAnimations;
  46963. for (var index = 0; index < runtimeAnimations.length; index++) {
  46964. if (runtimeAnimations[index].animation.targetProperty === property) {
  46965. return runtimeAnimations[index].animation;
  46966. }
  46967. }
  46968. return null;
  46969. };
  46970. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  46971. var runtimeAnimations = this._runtimeAnimations;
  46972. for (var index = 0; index < runtimeAnimations.length; index++) {
  46973. if (runtimeAnimations[index].animation.targetProperty === property) {
  46974. return runtimeAnimations[index];
  46975. }
  46976. }
  46977. return null;
  46978. };
  46979. Animatable.prototype.reset = function () {
  46980. var runtimeAnimations = this._runtimeAnimations;
  46981. for (var index = 0; index < runtimeAnimations.length; index++) {
  46982. runtimeAnimations[index].reset();
  46983. }
  46984. // Reset to original value
  46985. for (index = 0; index < runtimeAnimations.length; index++) {
  46986. var animation = runtimeAnimations[index];
  46987. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  46988. }
  46989. this._localDelayOffset = null;
  46990. this._pausedDelay = null;
  46991. };
  46992. Animatable.prototype.enableBlending = function (blendingSpeed) {
  46993. var runtimeAnimations = this._runtimeAnimations;
  46994. for (var index = 0; index < runtimeAnimations.length; index++) {
  46995. runtimeAnimations[index].animation.enableBlending = true;
  46996. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  46997. }
  46998. };
  46999. Animatable.prototype.disableBlending = function () {
  47000. var runtimeAnimations = this._runtimeAnimations;
  47001. for (var index = 0; index < runtimeAnimations.length; index++) {
  47002. runtimeAnimations[index].animation.enableBlending = false;
  47003. }
  47004. };
  47005. Animatable.prototype.goToFrame = function (frame) {
  47006. var runtimeAnimations = this._runtimeAnimations;
  47007. if (runtimeAnimations[0]) {
  47008. var fps = runtimeAnimations[0].animation.framePerSecond;
  47009. var currentFrame = runtimeAnimations[0].currentFrame;
  47010. var adjustTime = frame - currentFrame;
  47011. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47012. if (this._localDelayOffset === null) {
  47013. this._localDelayOffset = 0;
  47014. }
  47015. this._localDelayOffset -= delay;
  47016. }
  47017. for (var index = 0; index < runtimeAnimations.length; index++) {
  47018. runtimeAnimations[index].goToFrame(frame);
  47019. }
  47020. };
  47021. Animatable.prototype.pause = function () {
  47022. if (this._paused) {
  47023. return;
  47024. }
  47025. this._paused = true;
  47026. };
  47027. Animatable.prototype.restart = function () {
  47028. this._paused = false;
  47029. };
  47030. Animatable.prototype.stop = function (animationName) {
  47031. if (animationName) {
  47032. var idx = this._scene._activeAnimatables.indexOf(this);
  47033. if (idx > -1) {
  47034. var runtimeAnimations = this._runtimeAnimations;
  47035. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47036. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47037. continue;
  47038. }
  47039. runtimeAnimations[index].dispose();
  47040. runtimeAnimations.splice(index, 1);
  47041. }
  47042. if (runtimeAnimations.length == 0) {
  47043. this._scene._activeAnimatables.splice(idx, 1);
  47044. if (this.onAnimationEnd) {
  47045. this.onAnimationEnd();
  47046. }
  47047. }
  47048. }
  47049. }
  47050. else {
  47051. var index = this._scene._activeAnimatables.indexOf(this);
  47052. if (index > -1) {
  47053. this._scene._activeAnimatables.splice(index, 1);
  47054. var runtimeAnimations = this._runtimeAnimations;
  47055. for (var index = 0; index < runtimeAnimations.length; index++) {
  47056. runtimeAnimations[index].dispose();
  47057. }
  47058. if (this.onAnimationEnd) {
  47059. this.onAnimationEnd();
  47060. }
  47061. }
  47062. }
  47063. };
  47064. Animatable.prototype._animate = function (delay) {
  47065. if (this._paused) {
  47066. this.animationStarted = false;
  47067. if (this._pausedDelay === null) {
  47068. this._pausedDelay = delay;
  47069. }
  47070. return true;
  47071. }
  47072. if (this._localDelayOffset === null) {
  47073. this._localDelayOffset = delay;
  47074. this._pausedDelay = null;
  47075. }
  47076. else if (this._pausedDelay !== null) {
  47077. this._localDelayOffset += delay - this._pausedDelay;
  47078. this._pausedDelay = null;
  47079. }
  47080. // Animating
  47081. var running = false;
  47082. var runtimeAnimations = this._runtimeAnimations;
  47083. var index;
  47084. for (index = 0; index < runtimeAnimations.length; index++) {
  47085. var animation = runtimeAnimations[index];
  47086. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47087. running = running || isRunning;
  47088. }
  47089. this.animationStarted = running;
  47090. if (!running) {
  47091. // Remove from active animatables
  47092. index = this._scene._activeAnimatables.indexOf(this);
  47093. this._scene._activeAnimatables.splice(index, 1);
  47094. // Dispose all runtime animations
  47095. for (index = 0; index < runtimeAnimations.length; index++) {
  47096. runtimeAnimations[index].dispose();
  47097. }
  47098. }
  47099. if (!running && this.onAnimationEnd) {
  47100. this.onAnimationEnd();
  47101. this.onAnimationEnd = null;
  47102. }
  47103. return running;
  47104. };
  47105. return Animatable;
  47106. }());
  47107. BABYLON.Animatable = Animatable;
  47108. })(BABYLON || (BABYLON = {}));
  47109. //# sourceMappingURL=babylon.animatable.js.map
  47110. var BABYLON;
  47111. (function (BABYLON) {
  47112. var EasingFunction = /** @class */ (function () {
  47113. function EasingFunction() {
  47114. // Properties
  47115. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47116. }
  47117. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47118. get: function () {
  47119. return EasingFunction._EASINGMODE_EASEIN;
  47120. },
  47121. enumerable: true,
  47122. configurable: true
  47123. });
  47124. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47125. get: function () {
  47126. return EasingFunction._EASINGMODE_EASEOUT;
  47127. },
  47128. enumerable: true,
  47129. configurable: true
  47130. });
  47131. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47132. get: function () {
  47133. return EasingFunction._EASINGMODE_EASEINOUT;
  47134. },
  47135. enumerable: true,
  47136. configurable: true
  47137. });
  47138. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47139. var n = Math.min(Math.max(easingMode, 0), 2);
  47140. this._easingMode = n;
  47141. };
  47142. EasingFunction.prototype.getEasingMode = function () {
  47143. return this._easingMode;
  47144. };
  47145. EasingFunction.prototype.easeInCore = function (gradient) {
  47146. throw new Error('You must implement this method');
  47147. };
  47148. EasingFunction.prototype.ease = function (gradient) {
  47149. switch (this._easingMode) {
  47150. case EasingFunction.EASINGMODE_EASEIN:
  47151. return this.easeInCore(gradient);
  47152. case EasingFunction.EASINGMODE_EASEOUT:
  47153. return (1 - this.easeInCore(1 - gradient));
  47154. }
  47155. if (gradient >= 0.5) {
  47156. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47157. }
  47158. return (this.easeInCore(gradient * 2) * 0.5);
  47159. };
  47160. //Statics
  47161. EasingFunction._EASINGMODE_EASEIN = 0;
  47162. EasingFunction._EASINGMODE_EASEOUT = 1;
  47163. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47164. return EasingFunction;
  47165. }());
  47166. BABYLON.EasingFunction = EasingFunction;
  47167. var CircleEase = /** @class */ (function (_super) {
  47168. __extends(CircleEase, _super);
  47169. function CircleEase() {
  47170. return _super !== null && _super.apply(this, arguments) || this;
  47171. }
  47172. CircleEase.prototype.easeInCore = function (gradient) {
  47173. gradient = Math.max(0, Math.min(1, gradient));
  47174. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47175. };
  47176. return CircleEase;
  47177. }(EasingFunction));
  47178. BABYLON.CircleEase = CircleEase;
  47179. var BackEase = /** @class */ (function (_super) {
  47180. __extends(BackEase, _super);
  47181. function BackEase(amplitude) {
  47182. if (amplitude === void 0) { amplitude = 1; }
  47183. var _this = _super.call(this) || this;
  47184. _this.amplitude = amplitude;
  47185. return _this;
  47186. }
  47187. BackEase.prototype.easeInCore = function (gradient) {
  47188. var num = Math.max(0, this.amplitude);
  47189. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47190. };
  47191. return BackEase;
  47192. }(EasingFunction));
  47193. BABYLON.BackEase = BackEase;
  47194. var BounceEase = /** @class */ (function (_super) {
  47195. __extends(BounceEase, _super);
  47196. function BounceEase(bounces, bounciness) {
  47197. if (bounces === void 0) { bounces = 3; }
  47198. if (bounciness === void 0) { bounciness = 2; }
  47199. var _this = _super.call(this) || this;
  47200. _this.bounces = bounces;
  47201. _this.bounciness = bounciness;
  47202. return _this;
  47203. }
  47204. BounceEase.prototype.easeInCore = function (gradient) {
  47205. var y = Math.max(0.0, this.bounces);
  47206. var bounciness = this.bounciness;
  47207. if (bounciness <= 1.0) {
  47208. bounciness = 1.001;
  47209. }
  47210. var num9 = Math.pow(bounciness, y);
  47211. var num5 = 1.0 - bounciness;
  47212. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47213. var num15 = gradient * num4;
  47214. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47215. var num3 = Math.floor(num65);
  47216. var num13 = num3 + 1.0;
  47217. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47218. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47219. var num7 = (num8 + num12) * 0.5;
  47220. var num6 = gradient - num7;
  47221. var num2 = num7 - num8;
  47222. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47223. };
  47224. return BounceEase;
  47225. }(EasingFunction));
  47226. BABYLON.BounceEase = BounceEase;
  47227. var CubicEase = /** @class */ (function (_super) {
  47228. __extends(CubicEase, _super);
  47229. function CubicEase() {
  47230. return _super !== null && _super.apply(this, arguments) || this;
  47231. }
  47232. CubicEase.prototype.easeInCore = function (gradient) {
  47233. return (gradient * gradient * gradient);
  47234. };
  47235. return CubicEase;
  47236. }(EasingFunction));
  47237. BABYLON.CubicEase = CubicEase;
  47238. var ElasticEase = /** @class */ (function (_super) {
  47239. __extends(ElasticEase, _super);
  47240. function ElasticEase(oscillations, springiness) {
  47241. if (oscillations === void 0) { oscillations = 3; }
  47242. if (springiness === void 0) { springiness = 3; }
  47243. var _this = _super.call(this) || this;
  47244. _this.oscillations = oscillations;
  47245. _this.springiness = springiness;
  47246. return _this;
  47247. }
  47248. ElasticEase.prototype.easeInCore = function (gradient) {
  47249. var num2;
  47250. var num3 = Math.max(0.0, this.oscillations);
  47251. var num = Math.max(0.0, this.springiness);
  47252. if (num == 0) {
  47253. num2 = gradient;
  47254. }
  47255. else {
  47256. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47257. }
  47258. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47259. };
  47260. return ElasticEase;
  47261. }(EasingFunction));
  47262. BABYLON.ElasticEase = ElasticEase;
  47263. var ExponentialEase = /** @class */ (function (_super) {
  47264. __extends(ExponentialEase, _super);
  47265. function ExponentialEase(exponent) {
  47266. if (exponent === void 0) { exponent = 2; }
  47267. var _this = _super.call(this) || this;
  47268. _this.exponent = exponent;
  47269. return _this;
  47270. }
  47271. ExponentialEase.prototype.easeInCore = function (gradient) {
  47272. if (this.exponent <= 0) {
  47273. return gradient;
  47274. }
  47275. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47276. };
  47277. return ExponentialEase;
  47278. }(EasingFunction));
  47279. BABYLON.ExponentialEase = ExponentialEase;
  47280. var PowerEase = /** @class */ (function (_super) {
  47281. __extends(PowerEase, _super);
  47282. function PowerEase(power) {
  47283. if (power === void 0) { power = 2; }
  47284. var _this = _super.call(this) || this;
  47285. _this.power = power;
  47286. return _this;
  47287. }
  47288. PowerEase.prototype.easeInCore = function (gradient) {
  47289. var y = Math.max(0.0, this.power);
  47290. return Math.pow(gradient, y);
  47291. };
  47292. return PowerEase;
  47293. }(EasingFunction));
  47294. BABYLON.PowerEase = PowerEase;
  47295. var QuadraticEase = /** @class */ (function (_super) {
  47296. __extends(QuadraticEase, _super);
  47297. function QuadraticEase() {
  47298. return _super !== null && _super.apply(this, arguments) || this;
  47299. }
  47300. QuadraticEase.prototype.easeInCore = function (gradient) {
  47301. return (gradient * gradient);
  47302. };
  47303. return QuadraticEase;
  47304. }(EasingFunction));
  47305. BABYLON.QuadraticEase = QuadraticEase;
  47306. var QuarticEase = /** @class */ (function (_super) {
  47307. __extends(QuarticEase, _super);
  47308. function QuarticEase() {
  47309. return _super !== null && _super.apply(this, arguments) || this;
  47310. }
  47311. QuarticEase.prototype.easeInCore = function (gradient) {
  47312. return (gradient * gradient * gradient * gradient);
  47313. };
  47314. return QuarticEase;
  47315. }(EasingFunction));
  47316. BABYLON.QuarticEase = QuarticEase;
  47317. var QuinticEase = /** @class */ (function (_super) {
  47318. __extends(QuinticEase, _super);
  47319. function QuinticEase() {
  47320. return _super !== null && _super.apply(this, arguments) || this;
  47321. }
  47322. QuinticEase.prototype.easeInCore = function (gradient) {
  47323. return (gradient * gradient * gradient * gradient * gradient);
  47324. };
  47325. return QuinticEase;
  47326. }(EasingFunction));
  47327. BABYLON.QuinticEase = QuinticEase;
  47328. var SineEase = /** @class */ (function (_super) {
  47329. __extends(SineEase, _super);
  47330. function SineEase() {
  47331. return _super !== null && _super.apply(this, arguments) || this;
  47332. }
  47333. SineEase.prototype.easeInCore = function (gradient) {
  47334. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47335. };
  47336. return SineEase;
  47337. }(EasingFunction));
  47338. BABYLON.SineEase = SineEase;
  47339. var BezierCurveEase = /** @class */ (function (_super) {
  47340. __extends(BezierCurveEase, _super);
  47341. function BezierCurveEase(x1, y1, x2, y2) {
  47342. if (x1 === void 0) { x1 = 0; }
  47343. if (y1 === void 0) { y1 = 0; }
  47344. if (x2 === void 0) { x2 = 1; }
  47345. if (y2 === void 0) { y2 = 1; }
  47346. var _this = _super.call(this) || this;
  47347. _this.x1 = x1;
  47348. _this.y1 = y1;
  47349. _this.x2 = x2;
  47350. _this.y2 = y2;
  47351. return _this;
  47352. }
  47353. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47354. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47355. };
  47356. return BezierCurveEase;
  47357. }(EasingFunction));
  47358. BABYLON.BezierCurveEase = BezierCurveEase;
  47359. })(BABYLON || (BABYLON = {}));
  47360. //# sourceMappingURL=babylon.easing.js.map
  47361. var BABYLON;
  47362. (function (BABYLON) {
  47363. var Condition = /** @class */ (function () {
  47364. function Condition(actionManager) {
  47365. this._actionManager = actionManager;
  47366. }
  47367. Condition.prototype.isValid = function () {
  47368. return true;
  47369. };
  47370. Condition.prototype._getProperty = function (propertyPath) {
  47371. return this._actionManager._getProperty(propertyPath);
  47372. };
  47373. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47374. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47375. };
  47376. Condition.prototype.serialize = function () {
  47377. };
  47378. Condition.prototype._serialize = function (serializedCondition) {
  47379. return {
  47380. type: 2,
  47381. children: [],
  47382. name: serializedCondition.name,
  47383. properties: serializedCondition.properties
  47384. };
  47385. };
  47386. return Condition;
  47387. }());
  47388. BABYLON.Condition = Condition;
  47389. var ValueCondition = /** @class */ (function (_super) {
  47390. __extends(ValueCondition, _super);
  47391. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47392. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47393. var _this = _super.call(this, actionManager) || this;
  47394. _this.propertyPath = propertyPath;
  47395. _this.value = value;
  47396. _this.operator = operator;
  47397. _this._target = target;
  47398. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47399. _this._property = _this._getProperty(_this.propertyPath);
  47400. return _this;
  47401. }
  47402. Object.defineProperty(ValueCondition, "IsEqual", {
  47403. get: function () {
  47404. return ValueCondition._IsEqual;
  47405. },
  47406. enumerable: true,
  47407. configurable: true
  47408. });
  47409. Object.defineProperty(ValueCondition, "IsDifferent", {
  47410. get: function () {
  47411. return ValueCondition._IsDifferent;
  47412. },
  47413. enumerable: true,
  47414. configurable: true
  47415. });
  47416. Object.defineProperty(ValueCondition, "IsGreater", {
  47417. get: function () {
  47418. return ValueCondition._IsGreater;
  47419. },
  47420. enumerable: true,
  47421. configurable: true
  47422. });
  47423. Object.defineProperty(ValueCondition, "IsLesser", {
  47424. get: function () {
  47425. return ValueCondition._IsLesser;
  47426. },
  47427. enumerable: true,
  47428. configurable: true
  47429. });
  47430. // Methods
  47431. ValueCondition.prototype.isValid = function () {
  47432. switch (this.operator) {
  47433. case ValueCondition.IsGreater:
  47434. return this._effectiveTarget[this._property] > this.value;
  47435. case ValueCondition.IsLesser:
  47436. return this._effectiveTarget[this._property] < this.value;
  47437. case ValueCondition.IsEqual:
  47438. case ValueCondition.IsDifferent:
  47439. var check;
  47440. if (this.value.equals) {
  47441. check = this.value.equals(this._effectiveTarget[this._property]);
  47442. }
  47443. else {
  47444. check = this.value === this._effectiveTarget[this._property];
  47445. }
  47446. return this.operator === ValueCondition.IsEqual ? check : !check;
  47447. }
  47448. return false;
  47449. };
  47450. ValueCondition.prototype.serialize = function () {
  47451. return this._serialize({
  47452. name: "ValueCondition",
  47453. properties: [
  47454. BABYLON.Action._GetTargetProperty(this._target),
  47455. { name: "propertyPath", value: this.propertyPath },
  47456. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47457. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47458. ]
  47459. });
  47460. };
  47461. ValueCondition.GetOperatorName = function (operator) {
  47462. switch (operator) {
  47463. case ValueCondition._IsEqual: return "IsEqual";
  47464. case ValueCondition._IsDifferent: return "IsDifferent";
  47465. case ValueCondition._IsGreater: return "IsGreater";
  47466. case ValueCondition._IsLesser: return "IsLesser";
  47467. default: return "";
  47468. }
  47469. };
  47470. // Statics
  47471. ValueCondition._IsEqual = 0;
  47472. ValueCondition._IsDifferent = 1;
  47473. ValueCondition._IsGreater = 2;
  47474. ValueCondition._IsLesser = 3;
  47475. return ValueCondition;
  47476. }(Condition));
  47477. BABYLON.ValueCondition = ValueCondition;
  47478. var PredicateCondition = /** @class */ (function (_super) {
  47479. __extends(PredicateCondition, _super);
  47480. function PredicateCondition(actionManager, predicate) {
  47481. var _this = _super.call(this, actionManager) || this;
  47482. _this.predicate = predicate;
  47483. return _this;
  47484. }
  47485. PredicateCondition.prototype.isValid = function () {
  47486. return this.predicate();
  47487. };
  47488. return PredicateCondition;
  47489. }(Condition));
  47490. BABYLON.PredicateCondition = PredicateCondition;
  47491. var StateCondition = /** @class */ (function (_super) {
  47492. __extends(StateCondition, _super);
  47493. function StateCondition(actionManager, target, value) {
  47494. var _this = _super.call(this, actionManager) || this;
  47495. _this.value = value;
  47496. _this._target = target;
  47497. return _this;
  47498. }
  47499. // Methods
  47500. StateCondition.prototype.isValid = function () {
  47501. return this._target.state === this.value;
  47502. };
  47503. StateCondition.prototype.serialize = function () {
  47504. return this._serialize({
  47505. name: "StateCondition",
  47506. properties: [
  47507. BABYLON.Action._GetTargetProperty(this._target),
  47508. { name: "value", value: this.value }
  47509. ]
  47510. });
  47511. };
  47512. return StateCondition;
  47513. }(Condition));
  47514. BABYLON.StateCondition = StateCondition;
  47515. })(BABYLON || (BABYLON = {}));
  47516. //# sourceMappingURL=babylon.condition.js.map
  47517. var BABYLON;
  47518. (function (BABYLON) {
  47519. var Action = /** @class */ (function () {
  47520. function Action(triggerOptions, condition) {
  47521. this.triggerOptions = triggerOptions;
  47522. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47523. if (triggerOptions.parameter) {
  47524. this.trigger = triggerOptions.trigger;
  47525. this._triggerParameter = triggerOptions.parameter;
  47526. }
  47527. else {
  47528. this.trigger = triggerOptions;
  47529. }
  47530. this._nextActiveAction = this;
  47531. this._condition = condition;
  47532. }
  47533. // Methods
  47534. Action.prototype._prepare = function () {
  47535. };
  47536. Action.prototype.getTriggerParameter = function () {
  47537. return this._triggerParameter;
  47538. };
  47539. Action.prototype._executeCurrent = function (evt) {
  47540. if (this._nextActiveAction._condition) {
  47541. var condition = this._nextActiveAction._condition;
  47542. var currentRenderId = this._actionManager.getScene().getRenderId();
  47543. // We cache the current evaluation for the current frame
  47544. if (condition._evaluationId === currentRenderId) {
  47545. if (!condition._currentResult) {
  47546. return;
  47547. }
  47548. }
  47549. else {
  47550. condition._evaluationId = currentRenderId;
  47551. if (!condition.isValid()) {
  47552. condition._currentResult = false;
  47553. return;
  47554. }
  47555. condition._currentResult = true;
  47556. }
  47557. }
  47558. this.onBeforeExecuteObservable.notifyObservers(this);
  47559. this._nextActiveAction.execute(evt);
  47560. this.skipToNextActiveAction();
  47561. };
  47562. Action.prototype.execute = function (evt) {
  47563. };
  47564. Action.prototype.skipToNextActiveAction = function () {
  47565. if (this._nextActiveAction._child) {
  47566. if (!this._nextActiveAction._child._actionManager) {
  47567. this._nextActiveAction._child._actionManager = this._actionManager;
  47568. }
  47569. this._nextActiveAction = this._nextActiveAction._child;
  47570. }
  47571. else {
  47572. this._nextActiveAction = this;
  47573. }
  47574. };
  47575. Action.prototype.then = function (action) {
  47576. this._child = action;
  47577. action._actionManager = this._actionManager;
  47578. action._prepare();
  47579. return action;
  47580. };
  47581. Action.prototype._getProperty = function (propertyPath) {
  47582. return this._actionManager._getProperty(propertyPath);
  47583. };
  47584. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47585. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47586. };
  47587. Action.prototype.serialize = function (parent) {
  47588. };
  47589. // Called by BABYLON.Action objects in serialize(...). Internal use
  47590. Action.prototype._serialize = function (serializedAction, parent) {
  47591. var serializationObject = {
  47592. type: 1,
  47593. children: [],
  47594. name: serializedAction.name,
  47595. properties: serializedAction.properties || []
  47596. };
  47597. // Serialize child
  47598. if (this._child) {
  47599. this._child.serialize(serializationObject);
  47600. }
  47601. // Check if "this" has a condition
  47602. if (this._condition) {
  47603. var serializedCondition = this._condition.serialize();
  47604. serializedCondition.children.push(serializationObject);
  47605. if (parent) {
  47606. parent.children.push(serializedCondition);
  47607. }
  47608. return serializedCondition;
  47609. }
  47610. if (parent) {
  47611. parent.children.push(serializationObject);
  47612. }
  47613. return serializationObject;
  47614. };
  47615. Action._SerializeValueAsString = function (value) {
  47616. if (typeof value === "number") {
  47617. return value.toString();
  47618. }
  47619. if (typeof value === "boolean") {
  47620. return value ? "true" : "false";
  47621. }
  47622. if (value instanceof BABYLON.Vector2) {
  47623. return value.x + ", " + value.y;
  47624. }
  47625. if (value instanceof BABYLON.Vector3) {
  47626. return value.x + ", " + value.y + ", " + value.z;
  47627. }
  47628. if (value instanceof BABYLON.Color3) {
  47629. return value.r + ", " + value.g + ", " + value.b;
  47630. }
  47631. if (value instanceof BABYLON.Color4) {
  47632. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47633. }
  47634. return value; // string
  47635. };
  47636. Action._GetTargetProperty = function (target) {
  47637. return {
  47638. name: "target",
  47639. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47640. : target instanceof BABYLON.Light ? "LightProperties"
  47641. : target instanceof BABYLON.Camera ? "CameraProperties"
  47642. : "SceneProperties",
  47643. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47644. };
  47645. };
  47646. return Action;
  47647. }());
  47648. BABYLON.Action = Action;
  47649. })(BABYLON || (BABYLON = {}));
  47650. //# sourceMappingURL=babylon.action.js.map
  47651. var BABYLON;
  47652. (function (BABYLON) {
  47653. /**
  47654. * ActionEvent is the event beint sent when an action is triggered.
  47655. */
  47656. var ActionEvent = /** @class */ (function () {
  47657. /**
  47658. * @param source The mesh or sprite that triggered the action.
  47659. * @param pointerX The X mouse cursor position at the time of the event
  47660. * @param pointerY The Y mouse cursor position at the time of the event
  47661. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47662. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47663. */
  47664. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47665. this.source = source;
  47666. this.pointerX = pointerX;
  47667. this.pointerY = pointerY;
  47668. this.meshUnderPointer = meshUnderPointer;
  47669. this.sourceEvent = sourceEvent;
  47670. this.additionalData = additionalData;
  47671. }
  47672. /**
  47673. * Helper function to auto-create an ActionEvent from a source mesh.
  47674. * @param source The source mesh that triggered the event
  47675. * @param evt {Event} The original (browser) event
  47676. */
  47677. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47678. var scene = source.getScene();
  47679. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47680. };
  47681. /**
  47682. * Helper function to auto-create an ActionEvent from a source mesh.
  47683. * @param source The source sprite that triggered the event
  47684. * @param scene Scene associated with the sprite
  47685. * @param evt {Event} The original (browser) event
  47686. */
  47687. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  47688. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47689. };
  47690. /**
  47691. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  47692. * @param scene the scene where the event occurred
  47693. * @param evt {Event} The original (browser) event
  47694. */
  47695. ActionEvent.CreateNewFromScene = function (scene, evt) {
  47696. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  47697. };
  47698. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  47699. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  47700. };
  47701. return ActionEvent;
  47702. }());
  47703. BABYLON.ActionEvent = ActionEvent;
  47704. /**
  47705. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47706. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  47707. */
  47708. var ActionManager = /** @class */ (function () {
  47709. function ActionManager(scene) {
  47710. // Members
  47711. this.actions = new Array();
  47712. this.hoverCursor = '';
  47713. this._scene = scene;
  47714. scene._actionManagers.push(this);
  47715. }
  47716. Object.defineProperty(ActionManager, "NothingTrigger", {
  47717. get: function () {
  47718. return ActionManager._NothingTrigger;
  47719. },
  47720. enumerable: true,
  47721. configurable: true
  47722. });
  47723. Object.defineProperty(ActionManager, "OnPickTrigger", {
  47724. get: function () {
  47725. return ActionManager._OnPickTrigger;
  47726. },
  47727. enumerable: true,
  47728. configurable: true
  47729. });
  47730. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  47731. get: function () {
  47732. return ActionManager._OnLeftPickTrigger;
  47733. },
  47734. enumerable: true,
  47735. configurable: true
  47736. });
  47737. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  47738. get: function () {
  47739. return ActionManager._OnRightPickTrigger;
  47740. },
  47741. enumerable: true,
  47742. configurable: true
  47743. });
  47744. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  47745. get: function () {
  47746. return ActionManager._OnCenterPickTrigger;
  47747. },
  47748. enumerable: true,
  47749. configurable: true
  47750. });
  47751. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  47752. get: function () {
  47753. return ActionManager._OnPickDownTrigger;
  47754. },
  47755. enumerable: true,
  47756. configurable: true
  47757. });
  47758. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  47759. get: function () {
  47760. return ActionManager._OnDoublePickTrigger;
  47761. },
  47762. enumerable: true,
  47763. configurable: true
  47764. });
  47765. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  47766. get: function () {
  47767. return ActionManager._OnPickUpTrigger;
  47768. },
  47769. enumerable: true,
  47770. configurable: true
  47771. });
  47772. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  47773. /// This trigger will only be raised if you also declared a OnPickDown
  47774. get: function () {
  47775. return ActionManager._OnPickOutTrigger;
  47776. },
  47777. enumerable: true,
  47778. configurable: true
  47779. });
  47780. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  47781. get: function () {
  47782. return ActionManager._OnLongPressTrigger;
  47783. },
  47784. enumerable: true,
  47785. configurable: true
  47786. });
  47787. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  47788. get: function () {
  47789. return ActionManager._OnPointerOverTrigger;
  47790. },
  47791. enumerable: true,
  47792. configurable: true
  47793. });
  47794. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  47795. get: function () {
  47796. return ActionManager._OnPointerOutTrigger;
  47797. },
  47798. enumerable: true,
  47799. configurable: true
  47800. });
  47801. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  47802. get: function () {
  47803. return ActionManager._OnEveryFrameTrigger;
  47804. },
  47805. enumerable: true,
  47806. configurable: true
  47807. });
  47808. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  47809. get: function () {
  47810. return ActionManager._OnIntersectionEnterTrigger;
  47811. },
  47812. enumerable: true,
  47813. configurable: true
  47814. });
  47815. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  47816. get: function () {
  47817. return ActionManager._OnIntersectionExitTrigger;
  47818. },
  47819. enumerable: true,
  47820. configurable: true
  47821. });
  47822. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  47823. get: function () {
  47824. return ActionManager._OnKeyDownTrigger;
  47825. },
  47826. enumerable: true,
  47827. configurable: true
  47828. });
  47829. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  47830. get: function () {
  47831. return ActionManager._OnKeyUpTrigger;
  47832. },
  47833. enumerable: true,
  47834. configurable: true
  47835. });
  47836. // Methods
  47837. ActionManager.prototype.dispose = function () {
  47838. var index = this._scene._actionManagers.indexOf(this);
  47839. for (var i = 0; i < this.actions.length; i++) {
  47840. var action = this.actions[i];
  47841. ActionManager.Triggers[action.trigger]--;
  47842. if (ActionManager.Triggers[action.trigger] === 0) {
  47843. delete ActionManager.Triggers[action.trigger];
  47844. }
  47845. }
  47846. if (index > -1) {
  47847. this._scene._actionManagers.splice(index, 1);
  47848. }
  47849. };
  47850. ActionManager.prototype.getScene = function () {
  47851. return this._scene;
  47852. };
  47853. /**
  47854. * Does this action manager handles actions of any of the given triggers
  47855. * @param {number[]} triggers - the triggers to be tested
  47856. * @return {boolean} whether one (or more) of the triggers is handeled
  47857. */
  47858. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  47859. for (var index = 0; index < this.actions.length; index++) {
  47860. var action = this.actions[index];
  47861. if (triggers.indexOf(action.trigger) > -1) {
  47862. return true;
  47863. }
  47864. }
  47865. return false;
  47866. };
  47867. /**
  47868. * Does this action manager handles actions of a given trigger
  47869. * @param {number} trigger - the trigger to be tested
  47870. * @return {boolean} whether the trigger is handeled
  47871. */
  47872. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  47873. for (var index = 0; index < this.actions.length; index++) {
  47874. var action = this.actions[index];
  47875. if (action.trigger === trigger) {
  47876. return true;
  47877. }
  47878. }
  47879. return false;
  47880. };
  47881. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  47882. /**
  47883. * Does this action manager has pointer triggers
  47884. * @return {boolean} whether or not it has pointer triggers
  47885. */
  47886. get: function () {
  47887. for (var index = 0; index < this.actions.length; index++) {
  47888. var action = this.actions[index];
  47889. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  47890. return true;
  47891. }
  47892. }
  47893. return false;
  47894. },
  47895. enumerable: true,
  47896. configurable: true
  47897. });
  47898. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  47899. /**
  47900. * Does this action manager has pick triggers
  47901. * @return {boolean} whether or not it has pick triggers
  47902. */
  47903. get: function () {
  47904. for (var index = 0; index < this.actions.length; index++) {
  47905. var action = this.actions[index];
  47906. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  47907. return true;
  47908. }
  47909. }
  47910. return false;
  47911. },
  47912. enumerable: true,
  47913. configurable: true
  47914. });
  47915. Object.defineProperty(ActionManager, "HasTriggers", {
  47916. /**
  47917. * Does exist one action manager with at least one trigger
  47918. * @return {boolean} whether or not it exists one action manager with one trigger
  47919. **/
  47920. get: function () {
  47921. for (var t in ActionManager.Triggers) {
  47922. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47923. return true;
  47924. }
  47925. }
  47926. return false;
  47927. },
  47928. enumerable: true,
  47929. configurable: true
  47930. });
  47931. Object.defineProperty(ActionManager, "HasPickTriggers", {
  47932. /**
  47933. * Does exist one action manager with at least one pick trigger
  47934. * @return {boolean} whether or not it exists one action manager with one pick trigger
  47935. **/
  47936. get: function () {
  47937. for (var t in ActionManager.Triggers) {
  47938. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47939. var t_int = parseInt(t);
  47940. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  47941. return true;
  47942. }
  47943. }
  47944. }
  47945. return false;
  47946. },
  47947. enumerable: true,
  47948. configurable: true
  47949. });
  47950. /**
  47951. * Does exist one action manager that handles actions of a given trigger
  47952. * @param {number} trigger - the trigger to be tested
  47953. * @return {boolean} whether the trigger is handeled by at least one action manager
  47954. **/
  47955. ActionManager.HasSpecificTrigger = function (trigger) {
  47956. for (var t in ActionManager.Triggers) {
  47957. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47958. var t_int = parseInt(t);
  47959. if (t_int === trigger) {
  47960. return true;
  47961. }
  47962. }
  47963. }
  47964. return false;
  47965. };
  47966. /**
  47967. * Registers an action to this action manager
  47968. * @param {BABYLON.Action} action - the action to be registered
  47969. * @return {BABYLON.Action} the action amended (prepared) after registration
  47970. */
  47971. ActionManager.prototype.registerAction = function (action) {
  47972. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  47973. if (this.getScene().actionManager !== this) {
  47974. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  47975. return null;
  47976. }
  47977. }
  47978. this.actions.push(action);
  47979. if (ActionManager.Triggers[action.trigger]) {
  47980. ActionManager.Triggers[action.trigger]++;
  47981. }
  47982. else {
  47983. ActionManager.Triggers[action.trigger] = 1;
  47984. }
  47985. action._actionManager = this;
  47986. action._prepare();
  47987. return action;
  47988. };
  47989. /**
  47990. * Unregisters an action to this action manager
  47991. * @param action The action to be unregistered
  47992. * @return whether the action has been unregistered
  47993. */
  47994. ActionManager.prototype.unregisterAction = function (action) {
  47995. var index = this.actions.indexOf(action);
  47996. if (index !== -1) {
  47997. this.actions.splice(index, 1);
  47998. ActionManager.Triggers[action.trigger] -= 1;
  47999. if (ActionManager.Triggers[action.trigger] === 0) {
  48000. delete ActionManager.Triggers[action.trigger];
  48001. }
  48002. delete action._actionManager;
  48003. return true;
  48004. }
  48005. return false;
  48006. };
  48007. /**
  48008. * Process a specific trigger
  48009. * @param {number} trigger - the trigger to process
  48010. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48011. */
  48012. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48013. for (var index = 0; index < this.actions.length; index++) {
  48014. var action = this.actions[index];
  48015. if (action.trigger === trigger) {
  48016. if (evt) {
  48017. if (trigger === ActionManager.OnKeyUpTrigger
  48018. || trigger === ActionManager.OnKeyDownTrigger) {
  48019. var parameter = action.getTriggerParameter();
  48020. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48021. if (!parameter.toLowerCase) {
  48022. continue;
  48023. }
  48024. var lowerCase = parameter.toLowerCase();
  48025. if (lowerCase !== evt.sourceEvent.key) {
  48026. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48027. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48028. if (actualkey !== lowerCase) {
  48029. continue;
  48030. }
  48031. }
  48032. }
  48033. }
  48034. }
  48035. action._executeCurrent(evt);
  48036. }
  48037. }
  48038. };
  48039. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48040. var properties = propertyPath.split(".");
  48041. for (var index = 0; index < properties.length - 1; index++) {
  48042. target = target[properties[index]];
  48043. }
  48044. return target;
  48045. };
  48046. ActionManager.prototype._getProperty = function (propertyPath) {
  48047. var properties = propertyPath.split(".");
  48048. return properties[properties.length - 1];
  48049. };
  48050. ActionManager.prototype.serialize = function (name) {
  48051. var root = {
  48052. children: new Array(),
  48053. name: name,
  48054. type: 3,
  48055. properties: new Array() // Empty for root but required
  48056. };
  48057. for (var i = 0; i < this.actions.length; i++) {
  48058. var triggerObject = {
  48059. type: 0,
  48060. children: new Array(),
  48061. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48062. properties: new Array()
  48063. };
  48064. var triggerOptions = this.actions[i].triggerOptions;
  48065. if (triggerOptions && typeof triggerOptions !== "number") {
  48066. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48067. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48068. }
  48069. else {
  48070. var parameter = {};
  48071. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48072. if (triggerOptions.parameter.mesh) {
  48073. parameter._meshId = triggerOptions.parameter.mesh.id;
  48074. }
  48075. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48076. }
  48077. }
  48078. // Serialize child action, recursively
  48079. this.actions[i].serialize(triggerObject);
  48080. // Add serialized trigger
  48081. root.children.push(triggerObject);
  48082. }
  48083. return root;
  48084. };
  48085. ActionManager.Parse = function (parsedActions, object, scene) {
  48086. var actionManager = new ActionManager(scene);
  48087. if (object === null)
  48088. scene.actionManager = actionManager;
  48089. else
  48090. object.actionManager = actionManager;
  48091. // instanciate a new object
  48092. var instanciate = function (name, params) {
  48093. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48094. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48095. newInstance.constructor.apply(newInstance, params);
  48096. return newInstance;
  48097. };
  48098. var parseParameter = function (name, value, target, propertyPath) {
  48099. if (propertyPath === null) {
  48100. // String, boolean or float
  48101. var floatValue = parseFloat(value);
  48102. if (value === "true" || value === "false")
  48103. return value === "true";
  48104. else
  48105. return isNaN(floatValue) ? value : floatValue;
  48106. }
  48107. var effectiveTarget = propertyPath.split(".");
  48108. var values = value.split(",");
  48109. // Get effective Target
  48110. for (var i = 0; i < effectiveTarget.length; i++) {
  48111. target = target[effectiveTarget[i]];
  48112. }
  48113. // Return appropriate value with its type
  48114. if (typeof (target) === "boolean")
  48115. return values[0] === "true";
  48116. if (typeof (target) === "string")
  48117. return values[0];
  48118. // Parameters with multiple values such as Vector3 etc.
  48119. var split = new Array();
  48120. for (var i = 0; i < values.length; i++)
  48121. split.push(parseFloat(values[i]));
  48122. if (target instanceof BABYLON.Vector3)
  48123. return BABYLON.Vector3.FromArray(split);
  48124. if (target instanceof BABYLON.Vector4)
  48125. return BABYLON.Vector4.FromArray(split);
  48126. if (target instanceof BABYLON.Color3)
  48127. return BABYLON.Color3.FromArray(split);
  48128. if (target instanceof BABYLON.Color4)
  48129. return BABYLON.Color4.FromArray(split);
  48130. return parseFloat(values[0]);
  48131. };
  48132. // traverse graph per trigger
  48133. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48134. if (combineArray === void 0) { combineArray = null; }
  48135. if (parsedAction.detached)
  48136. return;
  48137. var parameters = new Array();
  48138. var target = null;
  48139. var propertyPath = null;
  48140. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48141. // Parameters
  48142. if (parsedAction.type === 2)
  48143. parameters.push(actionManager);
  48144. else
  48145. parameters.push(trigger);
  48146. if (combine) {
  48147. var actions = new Array();
  48148. for (var j = 0; j < parsedAction.combine.length; j++) {
  48149. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48150. }
  48151. parameters.push(actions);
  48152. }
  48153. else {
  48154. for (var i = 0; i < parsedAction.properties.length; i++) {
  48155. var value = parsedAction.properties[i].value;
  48156. var name = parsedAction.properties[i].name;
  48157. var targetType = parsedAction.properties[i].targetType;
  48158. if (name === "target")
  48159. if (targetType !== null && targetType === "SceneProperties")
  48160. value = target = scene;
  48161. else
  48162. value = target = scene.getNodeByName(value);
  48163. else if (name === "parent")
  48164. value = scene.getNodeByName(value);
  48165. else if (name === "sound")
  48166. value = scene.getSoundByName(value);
  48167. else if (name !== "propertyPath") {
  48168. if (parsedAction.type === 2 && name === "operator")
  48169. value = BABYLON.ValueCondition[value];
  48170. else
  48171. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48172. }
  48173. else {
  48174. propertyPath = value;
  48175. }
  48176. parameters.push(value);
  48177. }
  48178. }
  48179. if (combineArray === null) {
  48180. parameters.push(condition);
  48181. }
  48182. else {
  48183. parameters.push(null);
  48184. }
  48185. // If interpolate value action
  48186. if (parsedAction.name === "InterpolateValueAction") {
  48187. var param = parameters[parameters.length - 2];
  48188. parameters[parameters.length - 1] = param;
  48189. parameters[parameters.length - 2] = condition;
  48190. }
  48191. // Action or condition(s) and not CombineAction
  48192. var newAction = instanciate(parsedAction.name, parameters);
  48193. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48194. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48195. if (action)
  48196. action.then(nothing);
  48197. else
  48198. actionManager.registerAction(nothing);
  48199. action = nothing;
  48200. }
  48201. if (combineArray === null) {
  48202. if (newAction instanceof BABYLON.Condition) {
  48203. condition = newAction;
  48204. newAction = action;
  48205. }
  48206. else {
  48207. condition = null;
  48208. if (action)
  48209. action.then(newAction);
  48210. else
  48211. actionManager.registerAction(newAction);
  48212. }
  48213. }
  48214. else {
  48215. combineArray.push(newAction);
  48216. }
  48217. for (var i = 0; i < parsedAction.children.length; i++)
  48218. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48219. };
  48220. // triggers
  48221. for (var i = 0; i < parsedActions.children.length; i++) {
  48222. var triggerParams;
  48223. var trigger = parsedActions.children[i];
  48224. if (trigger.properties.length > 0) {
  48225. var param = trigger.properties[0].value;
  48226. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48227. if (value._meshId) {
  48228. value.mesh = scene.getMeshByID(value._meshId);
  48229. }
  48230. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48231. }
  48232. else
  48233. triggerParams = ActionManager[trigger.name];
  48234. for (var j = 0; j < trigger.children.length; j++) {
  48235. if (!trigger.detached)
  48236. traverse(trigger.children[j], triggerParams, null, null);
  48237. }
  48238. }
  48239. };
  48240. ActionManager.GetTriggerName = function (trigger) {
  48241. switch (trigger) {
  48242. case 0: return "NothingTrigger";
  48243. case 1: return "OnPickTrigger";
  48244. case 2: return "OnLeftPickTrigger";
  48245. case 3: return "OnRightPickTrigger";
  48246. case 4: return "OnCenterPickTrigger";
  48247. case 5: return "OnPickDownTrigger";
  48248. case 6: return "OnPickUpTrigger";
  48249. case 7: return "OnLongPressTrigger";
  48250. case 8: return "OnPointerOverTrigger";
  48251. case 9: return "OnPointerOutTrigger";
  48252. case 10: return "OnEveryFrameTrigger";
  48253. case 11: return "OnIntersectionEnterTrigger";
  48254. case 12: return "OnIntersectionExitTrigger";
  48255. case 13: return "OnKeyDownTrigger";
  48256. case 14: return "OnKeyUpTrigger";
  48257. case 15: return "OnPickOutTrigger";
  48258. default: return "";
  48259. }
  48260. };
  48261. // Statics
  48262. ActionManager._NothingTrigger = 0;
  48263. ActionManager._OnPickTrigger = 1;
  48264. ActionManager._OnLeftPickTrigger = 2;
  48265. ActionManager._OnRightPickTrigger = 3;
  48266. ActionManager._OnCenterPickTrigger = 4;
  48267. ActionManager._OnPickDownTrigger = 5;
  48268. ActionManager._OnDoublePickTrigger = 6;
  48269. ActionManager._OnPickUpTrigger = 7;
  48270. ActionManager._OnLongPressTrigger = 8;
  48271. ActionManager._OnPointerOverTrigger = 9;
  48272. ActionManager._OnPointerOutTrigger = 10;
  48273. ActionManager._OnEveryFrameTrigger = 11;
  48274. ActionManager._OnIntersectionEnterTrigger = 12;
  48275. ActionManager._OnIntersectionExitTrigger = 13;
  48276. ActionManager._OnKeyDownTrigger = 14;
  48277. ActionManager._OnKeyUpTrigger = 15;
  48278. ActionManager._OnPickOutTrigger = 16;
  48279. ActionManager.Triggers = {};
  48280. return ActionManager;
  48281. }());
  48282. BABYLON.ActionManager = ActionManager;
  48283. })(BABYLON || (BABYLON = {}));
  48284. //# sourceMappingURL=babylon.actionManager.js.map
  48285. var BABYLON;
  48286. (function (BABYLON) {
  48287. var InterpolateValueAction = /** @class */ (function (_super) {
  48288. __extends(InterpolateValueAction, _super);
  48289. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48290. if (duration === void 0) { duration = 1000; }
  48291. var _this = _super.call(this, triggerOptions, condition) || this;
  48292. _this.propertyPath = propertyPath;
  48293. _this.value = value;
  48294. _this.duration = duration;
  48295. _this.stopOtherAnimations = stopOtherAnimations;
  48296. _this.onInterpolationDone = onInterpolationDone;
  48297. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48298. _this._target = _this._effectiveTarget = target;
  48299. return _this;
  48300. }
  48301. InterpolateValueAction.prototype._prepare = function () {
  48302. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48303. this._property = this._getProperty(this.propertyPath);
  48304. };
  48305. InterpolateValueAction.prototype.execute = function () {
  48306. var _this = this;
  48307. var scene = this._actionManager.getScene();
  48308. var keys = [
  48309. {
  48310. frame: 0,
  48311. value: this._effectiveTarget[this._property]
  48312. }, {
  48313. frame: 100,
  48314. value: this.value
  48315. }
  48316. ];
  48317. var dataType;
  48318. if (typeof this.value === "number") {
  48319. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48320. }
  48321. else if (this.value instanceof BABYLON.Color3) {
  48322. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48323. }
  48324. else if (this.value instanceof BABYLON.Vector3) {
  48325. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48326. }
  48327. else if (this.value instanceof BABYLON.Matrix) {
  48328. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48329. }
  48330. else if (this.value instanceof BABYLON.Quaternion) {
  48331. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48332. }
  48333. else {
  48334. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48335. return;
  48336. }
  48337. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48338. animation.setKeys(keys);
  48339. if (this.stopOtherAnimations) {
  48340. scene.stopAnimation(this._effectiveTarget);
  48341. }
  48342. var wrapper = function () {
  48343. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48344. if (_this.onInterpolationDone) {
  48345. _this.onInterpolationDone();
  48346. }
  48347. };
  48348. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48349. };
  48350. InterpolateValueAction.prototype.serialize = function (parent) {
  48351. return _super.prototype._serialize.call(this, {
  48352. name: "InterpolateValueAction",
  48353. properties: [
  48354. BABYLON.Action._GetTargetProperty(this._target),
  48355. { name: "propertyPath", value: this.propertyPath },
  48356. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48357. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48358. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48359. ]
  48360. }, parent);
  48361. };
  48362. return InterpolateValueAction;
  48363. }(BABYLON.Action));
  48364. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48365. })(BABYLON || (BABYLON = {}));
  48366. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48367. var BABYLON;
  48368. (function (BABYLON) {
  48369. var SwitchBooleanAction = /** @class */ (function (_super) {
  48370. __extends(SwitchBooleanAction, _super);
  48371. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48372. var _this = _super.call(this, triggerOptions, condition) || this;
  48373. _this.propertyPath = propertyPath;
  48374. _this._target = _this._effectiveTarget = target;
  48375. return _this;
  48376. }
  48377. SwitchBooleanAction.prototype._prepare = function () {
  48378. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48379. this._property = this._getProperty(this.propertyPath);
  48380. };
  48381. SwitchBooleanAction.prototype.execute = function () {
  48382. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48383. };
  48384. SwitchBooleanAction.prototype.serialize = function (parent) {
  48385. return _super.prototype._serialize.call(this, {
  48386. name: "SwitchBooleanAction",
  48387. properties: [
  48388. BABYLON.Action._GetTargetProperty(this._target),
  48389. { name: "propertyPath", value: this.propertyPath }
  48390. ]
  48391. }, parent);
  48392. };
  48393. return SwitchBooleanAction;
  48394. }(BABYLON.Action));
  48395. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48396. var SetStateAction = /** @class */ (function (_super) {
  48397. __extends(SetStateAction, _super);
  48398. function SetStateAction(triggerOptions, target, value, condition) {
  48399. var _this = _super.call(this, triggerOptions, condition) || this;
  48400. _this.value = value;
  48401. _this._target = target;
  48402. return _this;
  48403. }
  48404. SetStateAction.prototype.execute = function () {
  48405. this._target.state = this.value;
  48406. };
  48407. SetStateAction.prototype.serialize = function (parent) {
  48408. return _super.prototype._serialize.call(this, {
  48409. name: "SetStateAction",
  48410. properties: [
  48411. BABYLON.Action._GetTargetProperty(this._target),
  48412. { name: "value", value: this.value }
  48413. ]
  48414. }, parent);
  48415. };
  48416. return SetStateAction;
  48417. }(BABYLON.Action));
  48418. BABYLON.SetStateAction = SetStateAction;
  48419. var SetValueAction = /** @class */ (function (_super) {
  48420. __extends(SetValueAction, _super);
  48421. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48422. var _this = _super.call(this, triggerOptions, condition) || this;
  48423. _this.propertyPath = propertyPath;
  48424. _this.value = value;
  48425. _this._target = _this._effectiveTarget = target;
  48426. return _this;
  48427. }
  48428. SetValueAction.prototype._prepare = function () {
  48429. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48430. this._property = this._getProperty(this.propertyPath);
  48431. };
  48432. SetValueAction.prototype.execute = function () {
  48433. this._effectiveTarget[this._property] = this.value;
  48434. if (this._target.markAsDirty) {
  48435. this._target.markAsDirty(this._property);
  48436. }
  48437. };
  48438. SetValueAction.prototype.serialize = function (parent) {
  48439. return _super.prototype._serialize.call(this, {
  48440. name: "SetValueAction",
  48441. properties: [
  48442. BABYLON.Action._GetTargetProperty(this._target),
  48443. { name: "propertyPath", value: this.propertyPath },
  48444. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48445. ]
  48446. }, parent);
  48447. };
  48448. return SetValueAction;
  48449. }(BABYLON.Action));
  48450. BABYLON.SetValueAction = SetValueAction;
  48451. var IncrementValueAction = /** @class */ (function (_super) {
  48452. __extends(IncrementValueAction, _super);
  48453. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48454. var _this = _super.call(this, triggerOptions, condition) || this;
  48455. _this.propertyPath = propertyPath;
  48456. _this.value = value;
  48457. _this._target = _this._effectiveTarget = target;
  48458. return _this;
  48459. }
  48460. IncrementValueAction.prototype._prepare = function () {
  48461. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48462. this._property = this._getProperty(this.propertyPath);
  48463. if (typeof this._effectiveTarget[this._property] !== "number") {
  48464. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48465. }
  48466. };
  48467. IncrementValueAction.prototype.execute = function () {
  48468. this._effectiveTarget[this._property] += this.value;
  48469. if (this._target.markAsDirty) {
  48470. this._target.markAsDirty(this._property);
  48471. }
  48472. };
  48473. IncrementValueAction.prototype.serialize = function (parent) {
  48474. return _super.prototype._serialize.call(this, {
  48475. name: "IncrementValueAction",
  48476. properties: [
  48477. BABYLON.Action._GetTargetProperty(this._target),
  48478. { name: "propertyPath", value: this.propertyPath },
  48479. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48480. ]
  48481. }, parent);
  48482. };
  48483. return IncrementValueAction;
  48484. }(BABYLON.Action));
  48485. BABYLON.IncrementValueAction = IncrementValueAction;
  48486. var PlayAnimationAction = /** @class */ (function (_super) {
  48487. __extends(PlayAnimationAction, _super);
  48488. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48489. var _this = _super.call(this, triggerOptions, condition) || this;
  48490. _this.from = from;
  48491. _this.to = to;
  48492. _this.loop = loop;
  48493. _this._target = target;
  48494. return _this;
  48495. }
  48496. PlayAnimationAction.prototype._prepare = function () {
  48497. };
  48498. PlayAnimationAction.prototype.execute = function () {
  48499. var scene = this._actionManager.getScene();
  48500. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48501. };
  48502. PlayAnimationAction.prototype.serialize = function (parent) {
  48503. return _super.prototype._serialize.call(this, {
  48504. name: "PlayAnimationAction",
  48505. properties: [
  48506. BABYLON.Action._GetTargetProperty(this._target),
  48507. { name: "from", value: String(this.from) },
  48508. { name: "to", value: String(this.to) },
  48509. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48510. ]
  48511. }, parent);
  48512. };
  48513. return PlayAnimationAction;
  48514. }(BABYLON.Action));
  48515. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48516. var StopAnimationAction = /** @class */ (function (_super) {
  48517. __extends(StopAnimationAction, _super);
  48518. function StopAnimationAction(triggerOptions, target, condition) {
  48519. var _this = _super.call(this, triggerOptions, condition) || this;
  48520. _this._target = target;
  48521. return _this;
  48522. }
  48523. StopAnimationAction.prototype._prepare = function () {
  48524. };
  48525. StopAnimationAction.prototype.execute = function () {
  48526. var scene = this._actionManager.getScene();
  48527. scene.stopAnimation(this._target);
  48528. };
  48529. StopAnimationAction.prototype.serialize = function (parent) {
  48530. return _super.prototype._serialize.call(this, {
  48531. name: "StopAnimationAction",
  48532. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48533. }, parent);
  48534. };
  48535. return StopAnimationAction;
  48536. }(BABYLON.Action));
  48537. BABYLON.StopAnimationAction = StopAnimationAction;
  48538. var DoNothingAction = /** @class */ (function (_super) {
  48539. __extends(DoNothingAction, _super);
  48540. function DoNothingAction(triggerOptions, condition) {
  48541. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48542. return _super.call(this, triggerOptions, condition) || this;
  48543. }
  48544. DoNothingAction.prototype.execute = function () {
  48545. };
  48546. DoNothingAction.prototype.serialize = function (parent) {
  48547. return _super.prototype._serialize.call(this, {
  48548. name: "DoNothingAction",
  48549. properties: []
  48550. }, parent);
  48551. };
  48552. return DoNothingAction;
  48553. }(BABYLON.Action));
  48554. BABYLON.DoNothingAction = DoNothingAction;
  48555. var CombineAction = /** @class */ (function (_super) {
  48556. __extends(CombineAction, _super);
  48557. function CombineAction(triggerOptions, children, condition) {
  48558. var _this = _super.call(this, triggerOptions, condition) || this;
  48559. _this.children = children;
  48560. return _this;
  48561. }
  48562. CombineAction.prototype._prepare = function () {
  48563. for (var index = 0; index < this.children.length; index++) {
  48564. this.children[index]._actionManager = this._actionManager;
  48565. this.children[index]._prepare();
  48566. }
  48567. };
  48568. CombineAction.prototype.execute = function (evt) {
  48569. for (var index = 0; index < this.children.length; index++) {
  48570. this.children[index].execute(evt);
  48571. }
  48572. };
  48573. CombineAction.prototype.serialize = function (parent) {
  48574. var serializationObject = _super.prototype._serialize.call(this, {
  48575. name: "CombineAction",
  48576. properties: [],
  48577. combine: []
  48578. }, parent);
  48579. for (var i = 0; i < this.children.length; i++) {
  48580. serializationObject.combine.push(this.children[i].serialize(null));
  48581. }
  48582. return serializationObject;
  48583. };
  48584. return CombineAction;
  48585. }(BABYLON.Action));
  48586. BABYLON.CombineAction = CombineAction;
  48587. var ExecuteCodeAction = /** @class */ (function (_super) {
  48588. __extends(ExecuteCodeAction, _super);
  48589. function ExecuteCodeAction(triggerOptions, func, condition) {
  48590. var _this = _super.call(this, triggerOptions, condition) || this;
  48591. _this.func = func;
  48592. return _this;
  48593. }
  48594. ExecuteCodeAction.prototype.execute = function (evt) {
  48595. this.func(evt);
  48596. };
  48597. return ExecuteCodeAction;
  48598. }(BABYLON.Action));
  48599. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48600. var SetParentAction = /** @class */ (function (_super) {
  48601. __extends(SetParentAction, _super);
  48602. function SetParentAction(triggerOptions, target, parent, condition) {
  48603. var _this = _super.call(this, triggerOptions, condition) || this;
  48604. _this._target = target;
  48605. _this._parent = parent;
  48606. return _this;
  48607. }
  48608. SetParentAction.prototype._prepare = function () {
  48609. };
  48610. SetParentAction.prototype.execute = function () {
  48611. if (this._target.parent === this._parent) {
  48612. return;
  48613. }
  48614. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48615. invertParentWorldMatrix.invert();
  48616. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48617. this._target.parent = this._parent;
  48618. };
  48619. SetParentAction.prototype.serialize = function (parent) {
  48620. return _super.prototype._serialize.call(this, {
  48621. name: "SetParentAction",
  48622. properties: [
  48623. BABYLON.Action._GetTargetProperty(this._target),
  48624. BABYLON.Action._GetTargetProperty(this._parent),
  48625. ]
  48626. }, parent);
  48627. };
  48628. return SetParentAction;
  48629. }(BABYLON.Action));
  48630. BABYLON.SetParentAction = SetParentAction;
  48631. var PlaySoundAction = /** @class */ (function (_super) {
  48632. __extends(PlaySoundAction, _super);
  48633. function PlaySoundAction(triggerOptions, sound, condition) {
  48634. var _this = _super.call(this, triggerOptions, condition) || this;
  48635. _this._sound = sound;
  48636. return _this;
  48637. }
  48638. PlaySoundAction.prototype._prepare = function () {
  48639. };
  48640. PlaySoundAction.prototype.execute = function () {
  48641. if (this._sound !== undefined)
  48642. this._sound.play();
  48643. };
  48644. PlaySoundAction.prototype.serialize = function (parent) {
  48645. return _super.prototype._serialize.call(this, {
  48646. name: "PlaySoundAction",
  48647. properties: [{ name: "sound", value: this._sound.name }]
  48648. }, parent);
  48649. };
  48650. return PlaySoundAction;
  48651. }(BABYLON.Action));
  48652. BABYLON.PlaySoundAction = PlaySoundAction;
  48653. var StopSoundAction = /** @class */ (function (_super) {
  48654. __extends(StopSoundAction, _super);
  48655. function StopSoundAction(triggerOptions, sound, condition) {
  48656. var _this = _super.call(this, triggerOptions, condition) || this;
  48657. _this._sound = sound;
  48658. return _this;
  48659. }
  48660. StopSoundAction.prototype._prepare = function () {
  48661. };
  48662. StopSoundAction.prototype.execute = function () {
  48663. if (this._sound !== undefined)
  48664. this._sound.stop();
  48665. };
  48666. StopSoundAction.prototype.serialize = function (parent) {
  48667. return _super.prototype._serialize.call(this, {
  48668. name: "StopSoundAction",
  48669. properties: [{ name: "sound", value: this._sound.name }]
  48670. }, parent);
  48671. };
  48672. return StopSoundAction;
  48673. }(BABYLON.Action));
  48674. BABYLON.StopSoundAction = StopSoundAction;
  48675. })(BABYLON || (BABYLON = {}));
  48676. //# sourceMappingURL=babylon.directActions.js.map
  48677. var BABYLON;
  48678. (function (BABYLON) {
  48679. var SpriteManager = /** @class */ (function () {
  48680. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  48681. if (epsilon === void 0) { epsilon = 0.01; }
  48682. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48683. this.name = name;
  48684. this.sprites = new Array();
  48685. this.renderingGroupId = 0;
  48686. this.layerMask = 0x0FFFFFFF;
  48687. this.fogEnabled = true;
  48688. this.isPickable = false;
  48689. /**
  48690. * An event triggered when the manager is disposed.
  48691. * @type {BABYLON.Observable}
  48692. */
  48693. this.onDisposeObservable = new BABYLON.Observable();
  48694. this._vertexBuffers = {};
  48695. this._capacity = capacity;
  48696. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  48697. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48698. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48699. if (cellSize.width && cellSize.height) {
  48700. this.cellWidth = cellSize.width;
  48701. this.cellHeight = cellSize.height;
  48702. }
  48703. else if (cellSize !== undefined) {
  48704. this.cellWidth = cellSize;
  48705. this.cellHeight = cellSize;
  48706. }
  48707. else {
  48708. return;
  48709. }
  48710. this._epsilon = epsilon;
  48711. this._scene = scene;
  48712. this._scene.spriteManagers.push(this);
  48713. var indices = [];
  48714. var index = 0;
  48715. for (var count = 0; count < capacity; count++) {
  48716. indices.push(index);
  48717. indices.push(index + 1);
  48718. indices.push(index + 2);
  48719. indices.push(index);
  48720. indices.push(index + 2);
  48721. indices.push(index + 3);
  48722. index += 4;
  48723. }
  48724. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  48725. // VBO
  48726. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  48727. this._vertexData = new Float32Array(capacity * 16 * 4);
  48728. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  48729. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  48730. var options = this._buffer.createVertexBuffer("options", 4, 4);
  48731. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  48732. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  48733. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48734. this._vertexBuffers["options"] = options;
  48735. this._vertexBuffers["cellInfo"] = cellInfo;
  48736. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48737. // Effects
  48738. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  48739. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  48740. }
  48741. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  48742. set: function (callback) {
  48743. if (this._onDisposeObserver) {
  48744. this.onDisposeObservable.remove(this._onDisposeObserver);
  48745. }
  48746. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48747. },
  48748. enumerable: true,
  48749. configurable: true
  48750. });
  48751. Object.defineProperty(SpriteManager.prototype, "texture", {
  48752. get: function () {
  48753. return this._spriteTexture;
  48754. },
  48755. set: function (value) {
  48756. this._spriteTexture = value;
  48757. },
  48758. enumerable: true,
  48759. configurable: true
  48760. });
  48761. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  48762. var arrayOffset = index * 16;
  48763. if (offsetX === 0)
  48764. offsetX = this._epsilon;
  48765. else if (offsetX === 1)
  48766. offsetX = 1 - this._epsilon;
  48767. if (offsetY === 0)
  48768. offsetY = this._epsilon;
  48769. else if (offsetY === 1)
  48770. offsetY = 1 - this._epsilon;
  48771. this._vertexData[arrayOffset] = sprite.position.x;
  48772. this._vertexData[arrayOffset + 1] = sprite.position.y;
  48773. this._vertexData[arrayOffset + 2] = sprite.position.z;
  48774. this._vertexData[arrayOffset + 3] = sprite.angle;
  48775. this._vertexData[arrayOffset + 4] = sprite.width;
  48776. this._vertexData[arrayOffset + 5] = sprite.height;
  48777. this._vertexData[arrayOffset + 6] = offsetX;
  48778. this._vertexData[arrayOffset + 7] = offsetY;
  48779. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  48780. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  48781. var offset = (sprite.cellIndex / rowSize) >> 0;
  48782. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  48783. this._vertexData[arrayOffset + 11] = offset;
  48784. // Color
  48785. this._vertexData[arrayOffset + 12] = sprite.color.r;
  48786. this._vertexData[arrayOffset + 13] = sprite.color.g;
  48787. this._vertexData[arrayOffset + 14] = sprite.color.b;
  48788. this._vertexData[arrayOffset + 15] = sprite.color.a;
  48789. };
  48790. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  48791. var count = Math.min(this._capacity, this.sprites.length);
  48792. var min = BABYLON.Vector3.Zero();
  48793. var max = BABYLON.Vector3.Zero();
  48794. var distance = Number.MAX_VALUE;
  48795. var currentSprite = null;
  48796. var cameraSpacePosition = BABYLON.Vector3.Zero();
  48797. var cameraView = camera.getViewMatrix();
  48798. for (var index = 0; index < count; index++) {
  48799. var sprite = this.sprites[index];
  48800. if (!sprite) {
  48801. continue;
  48802. }
  48803. if (predicate) {
  48804. if (!predicate(sprite)) {
  48805. continue;
  48806. }
  48807. }
  48808. else if (!sprite.isPickable) {
  48809. continue;
  48810. }
  48811. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  48812. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  48813. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  48814. if (ray.intersectsBoxMinMax(min, max)) {
  48815. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  48816. if (distance > currentDistance) {
  48817. distance = currentDistance;
  48818. currentSprite = sprite;
  48819. if (fastCheck) {
  48820. break;
  48821. }
  48822. }
  48823. }
  48824. }
  48825. if (currentSprite) {
  48826. var result = new BABYLON.PickingInfo();
  48827. result.hit = true;
  48828. result.pickedSprite = currentSprite;
  48829. result.distance = distance;
  48830. return result;
  48831. }
  48832. return null;
  48833. };
  48834. SpriteManager.prototype.render = function () {
  48835. // Check
  48836. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  48837. return;
  48838. var engine = this._scene.getEngine();
  48839. var baseSize = this._spriteTexture.getBaseSize();
  48840. // Sprites
  48841. var deltaTime = engine.getDeltaTime();
  48842. var max = Math.min(this._capacity, this.sprites.length);
  48843. var rowSize = baseSize.width / this.cellWidth;
  48844. var offset = 0;
  48845. for (var index = 0; index < max; index++) {
  48846. var sprite = this.sprites[index];
  48847. if (!sprite) {
  48848. continue;
  48849. }
  48850. sprite._animate(deltaTime);
  48851. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  48852. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  48853. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  48854. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  48855. }
  48856. this._buffer.update(this._vertexData);
  48857. // Render
  48858. var effect = this._effectBase;
  48859. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48860. effect = this._effectFog;
  48861. }
  48862. engine.enableEffect(effect);
  48863. var viewMatrix = this._scene.getViewMatrix();
  48864. effect.setTexture("diffuseSampler", this._spriteTexture);
  48865. effect.setMatrix("view", viewMatrix);
  48866. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48867. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  48868. // Fog
  48869. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48870. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  48871. effect.setColor3("vFogColor", this._scene.fogColor);
  48872. }
  48873. // VBOs
  48874. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48875. // Draw order
  48876. engine.setDepthFunctionToLessOrEqual();
  48877. effect.setBool("alphaTest", true);
  48878. engine.setColorWrite(false);
  48879. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48880. engine.setColorWrite(true);
  48881. effect.setBool("alphaTest", false);
  48882. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48883. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48884. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48885. };
  48886. SpriteManager.prototype.dispose = function () {
  48887. if (this._buffer) {
  48888. this._buffer.dispose();
  48889. this._buffer = null;
  48890. }
  48891. if (this._indexBuffer) {
  48892. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48893. this._indexBuffer = null;
  48894. }
  48895. if (this._spriteTexture) {
  48896. this._spriteTexture.dispose();
  48897. this._spriteTexture = null;
  48898. }
  48899. // Remove from scene
  48900. var index = this._scene.spriteManagers.indexOf(this);
  48901. this._scene.spriteManagers.splice(index, 1);
  48902. // Callback
  48903. this.onDisposeObservable.notifyObservers(this);
  48904. this.onDisposeObservable.clear();
  48905. };
  48906. return SpriteManager;
  48907. }());
  48908. BABYLON.SpriteManager = SpriteManager;
  48909. })(BABYLON || (BABYLON = {}));
  48910. //# sourceMappingURL=babylon.spriteManager.js.map
  48911. var BABYLON;
  48912. (function (BABYLON) {
  48913. var Sprite = /** @class */ (function () {
  48914. function Sprite(name, manager) {
  48915. this.name = name;
  48916. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48917. this.width = 1.0;
  48918. this.height = 1.0;
  48919. this.angle = 0;
  48920. this.cellIndex = 0;
  48921. this.invertU = 0;
  48922. this.invertV = 0;
  48923. this.animations = new Array();
  48924. this.isPickable = false;
  48925. this._animationStarted = false;
  48926. this._loopAnimation = false;
  48927. this._fromIndex = 0;
  48928. this._toIndex = 0;
  48929. this._delay = 0;
  48930. this._direction = 1;
  48931. this._time = 0;
  48932. this._manager = manager;
  48933. this._manager.sprites.push(this);
  48934. this.position = BABYLON.Vector3.Zero();
  48935. }
  48936. Object.defineProperty(Sprite.prototype, "size", {
  48937. get: function () {
  48938. return this.width;
  48939. },
  48940. set: function (value) {
  48941. this.width = value;
  48942. this.height = value;
  48943. },
  48944. enumerable: true,
  48945. configurable: true
  48946. });
  48947. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  48948. this._fromIndex = from;
  48949. this._toIndex = to;
  48950. this._loopAnimation = loop;
  48951. this._delay = delay;
  48952. this._animationStarted = true;
  48953. this._direction = from < to ? 1 : -1;
  48954. this.cellIndex = from;
  48955. this._time = 0;
  48956. this._onAnimationEnd = onAnimationEnd;
  48957. };
  48958. Sprite.prototype.stopAnimation = function () {
  48959. this._animationStarted = false;
  48960. };
  48961. Sprite.prototype._animate = function (deltaTime) {
  48962. if (!this._animationStarted)
  48963. return;
  48964. this._time += deltaTime;
  48965. if (this._time > this._delay) {
  48966. this._time = this._time % this._delay;
  48967. this.cellIndex += this._direction;
  48968. if (this.cellIndex > this._toIndex) {
  48969. if (this._loopAnimation) {
  48970. this.cellIndex = this._fromIndex;
  48971. }
  48972. else {
  48973. this.cellIndex = this._toIndex;
  48974. this._animationStarted = false;
  48975. if (this._onAnimationEnd) {
  48976. this._onAnimationEnd();
  48977. }
  48978. if (this.disposeWhenFinishedAnimating) {
  48979. this.dispose();
  48980. }
  48981. }
  48982. }
  48983. }
  48984. };
  48985. Sprite.prototype.dispose = function () {
  48986. for (var i = 0; i < this._manager.sprites.length; i++) {
  48987. if (this._manager.sprites[i] == this) {
  48988. this._manager.sprites.splice(i, 1);
  48989. }
  48990. }
  48991. };
  48992. return Sprite;
  48993. }());
  48994. BABYLON.Sprite = Sprite;
  48995. })(BABYLON || (BABYLON = {}));
  48996. //# sourceMappingURL=babylon.sprite.js.map
  48997. var BABYLON;
  48998. (function (BABYLON) {
  48999. var IntersectionInfo = /** @class */ (function () {
  49000. function IntersectionInfo(bu, bv, distance) {
  49001. this.bu = bu;
  49002. this.bv = bv;
  49003. this.distance = distance;
  49004. this.faceId = 0;
  49005. this.subMeshId = 0;
  49006. }
  49007. return IntersectionInfo;
  49008. }());
  49009. BABYLON.IntersectionInfo = IntersectionInfo;
  49010. var PickingInfo = /** @class */ (function () {
  49011. function PickingInfo() {
  49012. this.hit = false;
  49013. this.distance = 0;
  49014. this.pickedPoint = null;
  49015. this.pickedMesh = null;
  49016. this.bu = 0;
  49017. this.bv = 0;
  49018. this.faceId = -1;
  49019. this.subMeshId = 0;
  49020. this.pickedSprite = null;
  49021. }
  49022. // Methods
  49023. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49024. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49025. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49026. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49027. return null;
  49028. }
  49029. var indices = this.pickedMesh.getIndices();
  49030. if (!indices) {
  49031. return null;
  49032. }
  49033. var result;
  49034. if (useVerticesNormals) {
  49035. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49036. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49037. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49038. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49039. normal0 = normal0.scale(this.bu);
  49040. normal1 = normal1.scale(this.bv);
  49041. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49042. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49043. }
  49044. else {
  49045. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49046. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49047. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49048. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49049. var p1p2 = vertex1.subtract(vertex2);
  49050. var p3p2 = vertex3.subtract(vertex2);
  49051. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49052. }
  49053. if (useWorldCoordinates) {
  49054. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49055. }
  49056. return BABYLON.Vector3.Normalize(result);
  49057. };
  49058. PickingInfo.prototype.getTextureCoordinates = function () {
  49059. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49060. return null;
  49061. }
  49062. var indices = this.pickedMesh.getIndices();
  49063. if (!indices) {
  49064. return null;
  49065. }
  49066. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49067. if (!uvs) {
  49068. return null;
  49069. }
  49070. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49071. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49072. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49073. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49074. uv1 = uv1.scale(this.bu);
  49075. uv2 = uv2.scale(this.bv);
  49076. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49077. };
  49078. return PickingInfo;
  49079. }());
  49080. BABYLON.PickingInfo = PickingInfo;
  49081. })(BABYLON || (BABYLON = {}));
  49082. //# sourceMappingURL=babylon.pickingInfo.js.map
  49083. var BABYLON;
  49084. (function (BABYLON) {
  49085. var Ray = /** @class */ (function () {
  49086. function Ray(origin, direction, length) {
  49087. if (length === void 0) { length = Number.MAX_VALUE; }
  49088. this.origin = origin;
  49089. this.direction = direction;
  49090. this.length = length;
  49091. }
  49092. // Methods
  49093. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49094. var d = 0.0;
  49095. var maxValue = Number.MAX_VALUE;
  49096. var inv;
  49097. var min;
  49098. var max;
  49099. var temp;
  49100. if (Math.abs(this.direction.x) < 0.0000001) {
  49101. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49102. return false;
  49103. }
  49104. }
  49105. else {
  49106. inv = 1.0 / this.direction.x;
  49107. min = (minimum.x - this.origin.x) * inv;
  49108. max = (maximum.x - this.origin.x) * inv;
  49109. if (max === -Infinity) {
  49110. max = Infinity;
  49111. }
  49112. if (min > max) {
  49113. temp = min;
  49114. min = max;
  49115. max = temp;
  49116. }
  49117. d = Math.max(min, d);
  49118. maxValue = Math.min(max, maxValue);
  49119. if (d > maxValue) {
  49120. return false;
  49121. }
  49122. }
  49123. if (Math.abs(this.direction.y) < 0.0000001) {
  49124. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49125. return false;
  49126. }
  49127. }
  49128. else {
  49129. inv = 1.0 / this.direction.y;
  49130. min = (minimum.y - this.origin.y) * inv;
  49131. max = (maximum.y - this.origin.y) * inv;
  49132. if (max === -Infinity) {
  49133. max = Infinity;
  49134. }
  49135. if (min > max) {
  49136. temp = min;
  49137. min = max;
  49138. max = temp;
  49139. }
  49140. d = Math.max(min, d);
  49141. maxValue = Math.min(max, maxValue);
  49142. if (d > maxValue) {
  49143. return false;
  49144. }
  49145. }
  49146. if (Math.abs(this.direction.z) < 0.0000001) {
  49147. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49148. return false;
  49149. }
  49150. }
  49151. else {
  49152. inv = 1.0 / this.direction.z;
  49153. min = (minimum.z - this.origin.z) * inv;
  49154. max = (maximum.z - this.origin.z) * inv;
  49155. if (max === -Infinity) {
  49156. max = Infinity;
  49157. }
  49158. if (min > max) {
  49159. temp = min;
  49160. min = max;
  49161. max = temp;
  49162. }
  49163. d = Math.max(min, d);
  49164. maxValue = Math.min(max, maxValue);
  49165. if (d > maxValue) {
  49166. return false;
  49167. }
  49168. }
  49169. return true;
  49170. };
  49171. Ray.prototype.intersectsBox = function (box) {
  49172. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49173. };
  49174. Ray.prototype.intersectsSphere = function (sphere) {
  49175. var x = sphere.center.x - this.origin.x;
  49176. var y = sphere.center.y - this.origin.y;
  49177. var z = sphere.center.z - this.origin.z;
  49178. var pyth = (x * x) + (y * y) + (z * z);
  49179. var rr = sphere.radius * sphere.radius;
  49180. if (pyth <= rr) {
  49181. return true;
  49182. }
  49183. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49184. if (dot < 0.0) {
  49185. return false;
  49186. }
  49187. var temp = pyth - (dot * dot);
  49188. return temp <= rr;
  49189. };
  49190. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49191. if (!this._edge1) {
  49192. this._edge1 = BABYLON.Vector3.Zero();
  49193. this._edge2 = BABYLON.Vector3.Zero();
  49194. this._pvec = BABYLON.Vector3.Zero();
  49195. this._tvec = BABYLON.Vector3.Zero();
  49196. this._qvec = BABYLON.Vector3.Zero();
  49197. }
  49198. vertex1.subtractToRef(vertex0, this._edge1);
  49199. vertex2.subtractToRef(vertex0, this._edge2);
  49200. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49201. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49202. if (det === 0) {
  49203. return null;
  49204. }
  49205. var invdet = 1 / det;
  49206. this.origin.subtractToRef(vertex0, this._tvec);
  49207. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49208. if (bu < 0 || bu > 1.0) {
  49209. return null;
  49210. }
  49211. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49212. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49213. if (bv < 0 || bu + bv > 1.0) {
  49214. return null;
  49215. }
  49216. //check if the distance is longer than the predefined length.
  49217. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49218. if (distance > this.length) {
  49219. return null;
  49220. }
  49221. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49222. };
  49223. Ray.prototype.intersectsPlane = function (plane) {
  49224. var distance;
  49225. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49226. if (Math.abs(result1) < 9.99999997475243E-07) {
  49227. return null;
  49228. }
  49229. else {
  49230. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49231. distance = (-plane.d - result2) / result1;
  49232. if (distance < 0.0) {
  49233. if (distance < -9.99999997475243E-07) {
  49234. return null;
  49235. }
  49236. else {
  49237. return 0;
  49238. }
  49239. }
  49240. return distance;
  49241. }
  49242. };
  49243. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49244. var tm = BABYLON.Tmp.Matrix[0];
  49245. mesh.getWorldMatrix().invertToRef(tm);
  49246. if (this._tmpRay) {
  49247. Ray.TransformToRef(this, tm, this._tmpRay);
  49248. }
  49249. else {
  49250. this._tmpRay = Ray.Transform(this, tm);
  49251. }
  49252. return mesh.intersects(this._tmpRay, fastCheck);
  49253. };
  49254. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49255. if (results) {
  49256. results.length = 0;
  49257. }
  49258. else {
  49259. results = [];
  49260. }
  49261. for (var i = 0; i < meshes.length; i++) {
  49262. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49263. if (pickInfo.hit) {
  49264. results.push(pickInfo);
  49265. }
  49266. }
  49267. results.sort(this._comparePickingInfo);
  49268. return results;
  49269. };
  49270. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49271. if (pickingInfoA.distance < pickingInfoB.distance) {
  49272. return -1;
  49273. }
  49274. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49275. return 1;
  49276. }
  49277. else {
  49278. return 0;
  49279. }
  49280. };
  49281. /**
  49282. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49283. * @param sega the first point of the segment to test the intersection against
  49284. * @param segb the second point of the segment to test the intersection against
  49285. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49286. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49287. */
  49288. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49289. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49290. var u = segb.subtract(sega);
  49291. var v = rsegb.subtract(this.origin);
  49292. var w = sega.subtract(this.origin);
  49293. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49294. var b = BABYLON.Vector3.Dot(u, v);
  49295. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49296. var d = BABYLON.Vector3.Dot(u, w);
  49297. var e = BABYLON.Vector3.Dot(v, w);
  49298. var D = a * c - b * b; // always >= 0
  49299. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49300. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49301. // compute the line parameters of the two closest points
  49302. if (D < Ray.smallnum) {
  49303. sN = 0.0; // force using point P0 on segment S1
  49304. sD = 1.0; // to prevent possible division by 0.0 later
  49305. tN = e;
  49306. tD = c;
  49307. }
  49308. else {
  49309. sN = (b * e - c * d);
  49310. tN = (a * e - b * d);
  49311. if (sN < 0.0) {
  49312. sN = 0.0;
  49313. tN = e;
  49314. tD = c;
  49315. }
  49316. else if (sN > sD) {
  49317. sN = sD;
  49318. tN = e + b;
  49319. tD = c;
  49320. }
  49321. }
  49322. if (tN < 0.0) {
  49323. tN = 0.0;
  49324. // recompute sc for this edge
  49325. if (-d < 0.0) {
  49326. sN = 0.0;
  49327. }
  49328. else if (-d > a)
  49329. sN = sD;
  49330. else {
  49331. sN = -d;
  49332. sD = a;
  49333. }
  49334. }
  49335. else if (tN > tD) {
  49336. tN = tD;
  49337. // recompute sc for this edge
  49338. if ((-d + b) < 0.0) {
  49339. sN = 0;
  49340. }
  49341. else if ((-d + b) > a) {
  49342. sN = sD;
  49343. }
  49344. else {
  49345. sN = (-d + b);
  49346. sD = a;
  49347. }
  49348. }
  49349. // finally do the division to get sc and tc
  49350. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49351. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49352. // get the difference of the two closest points
  49353. var qtc = v.multiplyByFloats(tc, tc, tc);
  49354. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49355. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49356. if (isIntersected) {
  49357. return qtc.length();
  49358. }
  49359. return -1;
  49360. };
  49361. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49362. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49363. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49364. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49365. this.direction.normalize();
  49366. return this;
  49367. };
  49368. // Statics
  49369. Ray.Zero = function () {
  49370. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49371. };
  49372. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49373. var result = Ray.Zero();
  49374. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49375. };
  49376. /**
  49377. * 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
  49378. * transformed to the given world matrix.
  49379. * @param origin The origin point
  49380. * @param end The end point
  49381. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49382. */
  49383. Ray.CreateNewFromTo = function (origin, end, world) {
  49384. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49385. var direction = end.subtract(origin);
  49386. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49387. direction.normalize();
  49388. return Ray.Transform(new Ray(origin, direction, length), world);
  49389. };
  49390. Ray.Transform = function (ray, matrix) {
  49391. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49392. Ray.TransformToRef(ray, matrix, result);
  49393. return result;
  49394. };
  49395. Ray.TransformToRef = function (ray, matrix, result) {
  49396. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49397. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49398. result.length = ray.length;
  49399. var dir = result.direction;
  49400. var len = dir.length();
  49401. if (!(len === 0 || len === 1)) {
  49402. var num = 1.0 / len;
  49403. dir.x *= num;
  49404. dir.y *= num;
  49405. dir.z *= num;
  49406. result.length *= len;
  49407. }
  49408. };
  49409. Ray.smallnum = 0.00000001;
  49410. Ray.rayl = 10e8;
  49411. return Ray;
  49412. }());
  49413. BABYLON.Ray = Ray;
  49414. })(BABYLON || (BABYLON = {}));
  49415. //# sourceMappingURL=babylon.ray.js.map
  49416. var BABYLON;
  49417. (function (BABYLON) {
  49418. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49419. if (boxMin.x > sphereCenter.x + sphereRadius)
  49420. return false;
  49421. if (sphereCenter.x - sphereRadius > boxMax.x)
  49422. return false;
  49423. if (boxMin.y > sphereCenter.y + sphereRadius)
  49424. return false;
  49425. if (sphereCenter.y - sphereRadius > boxMax.y)
  49426. return false;
  49427. if (boxMin.z > sphereCenter.z + sphereRadius)
  49428. return false;
  49429. if (sphereCenter.z - sphereRadius > boxMax.z)
  49430. return false;
  49431. return true;
  49432. };
  49433. var getLowestRoot = (function () {
  49434. var result = { root: 0, found: false };
  49435. return function (a, b, c, maxR) {
  49436. result.root = 0;
  49437. result.found = false;
  49438. var determinant = b * b - 4.0 * a * c;
  49439. if (determinant < 0)
  49440. return result;
  49441. var sqrtD = Math.sqrt(determinant);
  49442. var r1 = (-b - sqrtD) / (2.0 * a);
  49443. var r2 = (-b + sqrtD) / (2.0 * a);
  49444. if (r1 > r2) {
  49445. var temp = r2;
  49446. r2 = r1;
  49447. r1 = temp;
  49448. }
  49449. if (r1 > 0 && r1 < maxR) {
  49450. result.root = r1;
  49451. result.found = true;
  49452. return result;
  49453. }
  49454. if (r2 > 0 && r2 < maxR) {
  49455. result.root = r2;
  49456. result.found = true;
  49457. return result;
  49458. }
  49459. return result;
  49460. };
  49461. })();
  49462. var Collider = /** @class */ (function () {
  49463. function Collider() {
  49464. this._collisionPoint = BABYLON.Vector3.Zero();
  49465. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49466. this._tempVector = BABYLON.Vector3.Zero();
  49467. this._tempVector2 = BABYLON.Vector3.Zero();
  49468. this._tempVector3 = BABYLON.Vector3.Zero();
  49469. this._tempVector4 = BABYLON.Vector3.Zero();
  49470. this._edge = BABYLON.Vector3.Zero();
  49471. this._baseToVertex = BABYLON.Vector3.Zero();
  49472. this._destinationPoint = BABYLON.Vector3.Zero();
  49473. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49474. this._displacementVector = BABYLON.Vector3.Zero();
  49475. this._radius = BABYLON.Vector3.One();
  49476. this._retry = 0;
  49477. this._basePointWorld = BABYLON.Vector3.Zero();
  49478. this._velocityWorld = BABYLON.Vector3.Zero();
  49479. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49480. this._collisionMask = -1;
  49481. }
  49482. Object.defineProperty(Collider.prototype, "collisionMask", {
  49483. get: function () {
  49484. return this._collisionMask;
  49485. },
  49486. set: function (mask) {
  49487. this._collisionMask = !isNaN(mask) ? mask : -1;
  49488. },
  49489. enumerable: true,
  49490. configurable: true
  49491. });
  49492. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49493. /**
  49494. * Gets the plane normal used to compute the sliding response (in local space)
  49495. */
  49496. get: function () {
  49497. return this._slidePlaneNormal;
  49498. },
  49499. enumerable: true,
  49500. configurable: true
  49501. });
  49502. // Methods
  49503. Collider.prototype._initialize = function (source, dir, e) {
  49504. this._velocity = dir;
  49505. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49506. this._basePoint = source;
  49507. source.multiplyToRef(this._radius, this._basePointWorld);
  49508. dir.multiplyToRef(this._radius, this._velocityWorld);
  49509. this._velocityWorldLength = this._velocityWorld.length();
  49510. this._epsilon = e;
  49511. this.collisionFound = false;
  49512. };
  49513. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49514. pa.subtractToRef(point, this._tempVector);
  49515. pb.subtractToRef(point, this._tempVector2);
  49516. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49517. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49518. if (d < 0)
  49519. return false;
  49520. pc.subtractToRef(point, this._tempVector3);
  49521. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49522. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49523. if (d < 0)
  49524. return false;
  49525. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49526. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49527. return d >= 0;
  49528. };
  49529. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49530. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49531. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49532. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49533. return false;
  49534. }
  49535. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49536. return false;
  49537. return true;
  49538. };
  49539. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49540. var t0;
  49541. var embeddedInPlane = false;
  49542. //defensive programming, actually not needed.
  49543. if (!trianglePlaneArray) {
  49544. trianglePlaneArray = [];
  49545. }
  49546. if (!trianglePlaneArray[faceIndex]) {
  49547. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49548. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49549. }
  49550. var trianglePlane = trianglePlaneArray[faceIndex];
  49551. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49552. return;
  49553. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49554. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49555. if (normalDotVelocity == 0) {
  49556. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49557. return;
  49558. embeddedInPlane = true;
  49559. t0 = 0;
  49560. }
  49561. else {
  49562. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49563. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49564. if (t0 > t1) {
  49565. var temp = t1;
  49566. t1 = t0;
  49567. t0 = temp;
  49568. }
  49569. if (t0 > 1.0 || t1 < 0.0)
  49570. return;
  49571. if (t0 < 0)
  49572. t0 = 0;
  49573. if (t0 > 1.0)
  49574. t0 = 1.0;
  49575. }
  49576. this._collisionPoint.copyFromFloats(0, 0, 0);
  49577. var found = false;
  49578. var t = 1.0;
  49579. if (!embeddedInPlane) {
  49580. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49581. this._velocity.scaleToRef(t0, this._tempVector);
  49582. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49583. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49584. found = true;
  49585. t = t0;
  49586. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49587. }
  49588. }
  49589. if (!found) {
  49590. var velocitySquaredLength = this._velocity.lengthSquared();
  49591. var a = velocitySquaredLength;
  49592. this._basePoint.subtractToRef(p1, this._tempVector);
  49593. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49594. var c = this._tempVector.lengthSquared() - 1.0;
  49595. var lowestRoot = getLowestRoot(a, b, c, t);
  49596. if (lowestRoot.found) {
  49597. t = lowestRoot.root;
  49598. found = true;
  49599. this._collisionPoint.copyFrom(p1);
  49600. }
  49601. this._basePoint.subtractToRef(p2, this._tempVector);
  49602. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49603. c = this._tempVector.lengthSquared() - 1.0;
  49604. lowestRoot = getLowestRoot(a, b, c, t);
  49605. if (lowestRoot.found) {
  49606. t = lowestRoot.root;
  49607. found = true;
  49608. this._collisionPoint.copyFrom(p2);
  49609. }
  49610. this._basePoint.subtractToRef(p3, this._tempVector);
  49611. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49612. c = this._tempVector.lengthSquared() - 1.0;
  49613. lowestRoot = getLowestRoot(a, b, c, t);
  49614. if (lowestRoot.found) {
  49615. t = lowestRoot.root;
  49616. found = true;
  49617. this._collisionPoint.copyFrom(p3);
  49618. }
  49619. p2.subtractToRef(p1, this._edge);
  49620. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49621. var edgeSquaredLength = this._edge.lengthSquared();
  49622. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49623. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49624. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49625. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49626. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49627. lowestRoot = getLowestRoot(a, b, c, t);
  49628. if (lowestRoot.found) {
  49629. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49630. if (f >= 0.0 && f <= 1.0) {
  49631. t = lowestRoot.root;
  49632. found = true;
  49633. this._edge.scaleInPlace(f);
  49634. p1.addToRef(this._edge, this._collisionPoint);
  49635. }
  49636. }
  49637. p3.subtractToRef(p2, this._edge);
  49638. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49639. edgeSquaredLength = this._edge.lengthSquared();
  49640. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49641. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49642. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49643. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49644. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49645. lowestRoot = getLowestRoot(a, b, c, t);
  49646. if (lowestRoot.found) {
  49647. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49648. if (f >= 0.0 && f <= 1.0) {
  49649. t = lowestRoot.root;
  49650. found = true;
  49651. this._edge.scaleInPlace(f);
  49652. p2.addToRef(this._edge, this._collisionPoint);
  49653. }
  49654. }
  49655. p1.subtractToRef(p3, this._edge);
  49656. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49657. edgeSquaredLength = this._edge.lengthSquared();
  49658. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49659. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49660. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49661. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49662. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49663. lowestRoot = getLowestRoot(a, b, c, t);
  49664. if (lowestRoot.found) {
  49665. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49666. if (f >= 0.0 && f <= 1.0) {
  49667. t = lowestRoot.root;
  49668. found = true;
  49669. this._edge.scaleInPlace(f);
  49670. p3.addToRef(this._edge, this._collisionPoint);
  49671. }
  49672. }
  49673. }
  49674. if (found) {
  49675. var distToCollision = t * this._velocity.length();
  49676. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49677. if (!this.intersectionPoint) {
  49678. this.intersectionPoint = this._collisionPoint.clone();
  49679. }
  49680. else {
  49681. this.intersectionPoint.copyFrom(this._collisionPoint);
  49682. }
  49683. this._nearestDistance = distToCollision;
  49684. this.collisionFound = true;
  49685. }
  49686. }
  49687. };
  49688. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  49689. for (var i = indexStart; i < indexEnd; i += 3) {
  49690. var p1 = pts[indices[i] - decal];
  49691. var p2 = pts[indices[i + 1] - decal];
  49692. var p3 = pts[indices[i + 2] - decal];
  49693. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  49694. }
  49695. };
  49696. Collider.prototype._getResponse = function (pos, vel) {
  49697. pos.addToRef(vel, this._destinationPoint);
  49698. vel.scaleInPlace((this._nearestDistance / vel.length()));
  49699. this._basePoint.addToRef(vel, pos);
  49700. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  49701. this._slidePlaneNormal.normalize();
  49702. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  49703. pos.addInPlace(this._displacementVector);
  49704. this.intersectionPoint.addInPlace(this._displacementVector);
  49705. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  49706. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  49707. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  49708. };
  49709. return Collider;
  49710. }());
  49711. BABYLON.Collider = Collider;
  49712. })(BABYLON || (BABYLON = {}));
  49713. //# sourceMappingURL=babylon.collider.js.map
  49714. var BABYLON;
  49715. (function (BABYLON) {
  49716. //WebWorker code will be inserted to this variable.
  49717. BABYLON.CollisionWorker = "";
  49718. var WorkerTaskType;
  49719. (function (WorkerTaskType) {
  49720. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  49721. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  49722. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  49723. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  49724. var WorkerReplyType;
  49725. (function (WorkerReplyType) {
  49726. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  49727. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  49728. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  49729. var CollisionCoordinatorWorker = /** @class */ (function () {
  49730. function CollisionCoordinatorWorker() {
  49731. var _this = this;
  49732. this._scaledPosition = BABYLON.Vector3.Zero();
  49733. this._scaledVelocity = BABYLON.Vector3.Zero();
  49734. this.onMeshUpdated = function (transformNode) {
  49735. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  49736. };
  49737. this.onGeometryUpdated = function (geometry) {
  49738. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  49739. };
  49740. this._afterRender = function () {
  49741. if (!_this._init)
  49742. return;
  49743. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  49744. return;
  49745. }
  49746. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  49747. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  49748. if (_this._runningUpdated > 4) {
  49749. return;
  49750. }
  49751. ++_this._runningUpdated;
  49752. var payload = {
  49753. updatedMeshes: _this._addUpdateMeshesList,
  49754. updatedGeometries: _this._addUpdateGeometriesList,
  49755. removedGeometries: _this._toRemoveGeometryArray,
  49756. removedMeshes: _this._toRemoveMeshesArray
  49757. };
  49758. var message = {
  49759. payload: payload,
  49760. taskType: WorkerTaskType.UPDATE
  49761. };
  49762. var serializable = [];
  49763. for (var id in payload.updatedGeometries) {
  49764. if (payload.updatedGeometries.hasOwnProperty(id)) {
  49765. //prepare transferables
  49766. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  49767. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  49768. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  49769. }
  49770. }
  49771. _this._worker.postMessage(message, serializable);
  49772. _this._addUpdateMeshesList = {};
  49773. _this._addUpdateGeometriesList = {};
  49774. _this._toRemoveGeometryArray = [];
  49775. _this._toRemoveMeshesArray = [];
  49776. };
  49777. this._onMessageFromWorker = function (e) {
  49778. var returnData = e.data;
  49779. if (returnData.error != WorkerReplyType.SUCCESS) {
  49780. //TODO what errors can be returned from the worker?
  49781. BABYLON.Tools.Warn("error returned from worker!");
  49782. return;
  49783. }
  49784. switch (returnData.taskType) {
  49785. case WorkerTaskType.INIT:
  49786. _this._init = true;
  49787. //Update the worked with ALL of the scene's current state
  49788. _this._scene.meshes.forEach(function (mesh) {
  49789. _this.onMeshAdded(mesh);
  49790. });
  49791. _this._scene.getGeometries().forEach(function (geometry) {
  49792. _this.onGeometryAdded(geometry);
  49793. });
  49794. break;
  49795. case WorkerTaskType.UPDATE:
  49796. _this._runningUpdated--;
  49797. break;
  49798. case WorkerTaskType.COLLIDE:
  49799. var returnPayload = returnData.payload;
  49800. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  49801. return;
  49802. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  49803. if (callback) {
  49804. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  49805. if (mesh) {
  49806. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  49807. }
  49808. }
  49809. //cleanup
  49810. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  49811. break;
  49812. }
  49813. };
  49814. this._collisionsCallbackArray = [];
  49815. this._init = false;
  49816. this._runningUpdated = 0;
  49817. this._addUpdateMeshesList = {};
  49818. this._addUpdateGeometriesList = {};
  49819. this._toRemoveGeometryArray = [];
  49820. this._toRemoveMeshesArray = [];
  49821. }
  49822. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49823. if (!this._init)
  49824. return;
  49825. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  49826. return;
  49827. position.divideToRef(collider._radius, this._scaledPosition);
  49828. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49829. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  49830. var payload = {
  49831. collider: {
  49832. position: this._scaledPosition.asArray(),
  49833. velocity: this._scaledVelocity.asArray(),
  49834. radius: collider._radius.asArray()
  49835. },
  49836. collisionId: collisionIndex,
  49837. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  49838. maximumRetry: maximumRetry
  49839. };
  49840. var message = {
  49841. payload: payload,
  49842. taskType: WorkerTaskType.COLLIDE
  49843. };
  49844. this._worker.postMessage(message);
  49845. };
  49846. CollisionCoordinatorWorker.prototype.init = function (scene) {
  49847. this._scene = scene;
  49848. this._scene.registerAfterRender(this._afterRender);
  49849. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  49850. this._worker = new Worker(workerUrl);
  49851. this._worker.onmessage = this._onMessageFromWorker;
  49852. var message = {
  49853. payload: {},
  49854. taskType: WorkerTaskType.INIT
  49855. };
  49856. this._worker.postMessage(message);
  49857. };
  49858. CollisionCoordinatorWorker.prototype.destroy = function () {
  49859. this._scene.unregisterAfterRender(this._afterRender);
  49860. this._worker.terminate();
  49861. };
  49862. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  49863. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  49864. this.onMeshUpdated(mesh);
  49865. };
  49866. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  49867. this._toRemoveMeshesArray.push(mesh.uniqueId);
  49868. };
  49869. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  49870. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  49871. geometry.onGeometryUpdated = this.onGeometryUpdated;
  49872. this.onGeometryUpdated(geometry);
  49873. };
  49874. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  49875. this._toRemoveGeometryArray.push(geometry.id);
  49876. };
  49877. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  49878. var submeshes = [];
  49879. if (mesh.subMeshes) {
  49880. submeshes = mesh.subMeshes.map(function (sm, idx) {
  49881. var boundingInfo = sm.getBoundingInfo();
  49882. return {
  49883. position: idx,
  49884. verticesStart: sm.verticesStart,
  49885. verticesCount: sm.verticesCount,
  49886. indexStart: sm.indexStart,
  49887. indexCount: sm.indexCount,
  49888. hasMaterial: !!sm.getMaterial(),
  49889. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49890. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49891. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49892. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  49893. };
  49894. });
  49895. }
  49896. var geometryId = null;
  49897. if (mesh instanceof BABYLON.Mesh) {
  49898. var geometry = mesh.geometry;
  49899. geometryId = geometry ? geometry.id : null;
  49900. }
  49901. else if (mesh instanceof BABYLON.InstancedMesh) {
  49902. var geometry = mesh.sourceMesh.geometry;
  49903. geometryId = geometry ? geometry.id : null;
  49904. }
  49905. var boundingInfo = mesh.getBoundingInfo();
  49906. return {
  49907. uniqueId: mesh.uniqueId,
  49908. id: mesh.id,
  49909. name: mesh.name,
  49910. geometryId: geometryId,
  49911. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49912. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49913. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49914. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  49915. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  49916. subMeshes: submeshes,
  49917. checkCollisions: mesh.checkCollisions
  49918. };
  49919. };
  49920. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  49921. return {
  49922. id: geometry.id,
  49923. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  49924. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  49925. indices: new Uint32Array(geometry.getIndices() || []),
  49926. };
  49927. };
  49928. return CollisionCoordinatorWorker;
  49929. }());
  49930. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  49931. var CollisionCoordinatorLegacy = /** @class */ (function () {
  49932. function CollisionCoordinatorLegacy() {
  49933. this._scaledPosition = BABYLON.Vector3.Zero();
  49934. this._scaledVelocity = BABYLON.Vector3.Zero();
  49935. this._finalPosition = BABYLON.Vector3.Zero();
  49936. }
  49937. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49938. position.divideToRef(collider._radius, this._scaledPosition);
  49939. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49940. collider.collidedMesh = null;
  49941. collider._retry = 0;
  49942. collider._initialVelocity = this._scaledVelocity;
  49943. collider._initialPosition = this._scaledPosition;
  49944. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  49945. this._finalPosition.multiplyInPlace(collider._radius);
  49946. //run the callback
  49947. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  49948. };
  49949. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  49950. this._scene = scene;
  49951. };
  49952. CollisionCoordinatorLegacy.prototype.destroy = function () {
  49953. //Legacy need no destruction method.
  49954. };
  49955. //No update in legacy mode
  49956. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  49957. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  49958. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  49959. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  49960. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  49961. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  49962. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  49963. if (excludedMesh === void 0) { excludedMesh = null; }
  49964. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  49965. if (collider._retry >= maximumRetry) {
  49966. finalPosition.copyFrom(position);
  49967. return;
  49968. }
  49969. // Check if this is a mesh else camera or -1
  49970. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  49971. collider._initialize(position, velocity, closeDistance);
  49972. // Check all meshes
  49973. for (var index = 0; index < this._scene.meshes.length; index++) {
  49974. var mesh = this._scene.meshes[index];
  49975. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  49976. mesh._checkCollision(collider);
  49977. }
  49978. }
  49979. if (!collider.collisionFound) {
  49980. position.addToRef(velocity, finalPosition);
  49981. return;
  49982. }
  49983. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  49984. collider._getResponse(position, velocity);
  49985. }
  49986. if (velocity.length() <= closeDistance) {
  49987. finalPosition.copyFrom(position);
  49988. return;
  49989. }
  49990. collider._retry++;
  49991. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  49992. };
  49993. return CollisionCoordinatorLegacy;
  49994. }());
  49995. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  49996. })(BABYLON || (BABYLON = {}));
  49997. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  49998. var BABYLON;
  49999. (function (BABYLON) {
  50000. /**
  50001. * A particle represents one of the element emitted by a particle system.
  50002. * This is mainly define by its coordinates, direction, velocity and age.
  50003. */
  50004. var Particle = /** @class */ (function () {
  50005. /**
  50006. * Creates a new instance of @see Particle
  50007. * @param particleSystem the particle system the particle belongs to
  50008. */
  50009. function Particle(particleSystem) {
  50010. this.particleSystem = particleSystem;
  50011. /**
  50012. * The world position of the particle in the scene.
  50013. */
  50014. this.position = BABYLON.Vector3.Zero();
  50015. /**
  50016. * The world direction of the particle in the scene.
  50017. */
  50018. this.direction = BABYLON.Vector3.Zero();
  50019. /**
  50020. * The color of the particle.
  50021. */
  50022. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50023. /**
  50024. * The color change of the particle per step.
  50025. */
  50026. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50027. /**
  50028. * Defines how long will the life of the particle be.
  50029. */
  50030. this.lifeTime = 1.0;
  50031. /**
  50032. * The current age of the particle.
  50033. */
  50034. this.age = 0;
  50035. /**
  50036. * The current size of the particle.
  50037. */
  50038. this.size = 0;
  50039. /**
  50040. * The current angle of the particle.
  50041. */
  50042. this.angle = 0;
  50043. /**
  50044. * Defines how fast is the angle changing.
  50045. */
  50046. this.angularSpeed = 0;
  50047. /**
  50048. * Defines the cell index used by the particle to be rendered from a sprite.
  50049. */
  50050. this.cellIndex = 0;
  50051. this._currentFrameCounter = 0;
  50052. if (!this.particleSystem.isAnimationSheetEnabled) {
  50053. return;
  50054. }
  50055. this.cellIndex = this.particleSystem.startSpriteCellID;
  50056. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50057. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50058. }
  50059. else {
  50060. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50061. }
  50062. }
  50063. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50064. // (ageOffset / scaledUpdateSpeed) / available cells
  50065. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50066. this._currentFrameCounter += scaledUpdateSpeed;
  50067. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50068. this._currentFrameCounter = 0;
  50069. this.cellIndex++;
  50070. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50071. this.cellIndex = this.particleSystem.endSpriteCellID;
  50072. }
  50073. }
  50074. };
  50075. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50076. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50077. this.cellIndex++;
  50078. this._currentFrameCounter = 0;
  50079. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50080. if (this.particleSystem.spriteCellLoop) {
  50081. this.cellIndex = this.particleSystem.startSpriteCellID;
  50082. }
  50083. else {
  50084. this.cellIndex = this.particleSystem.endSpriteCellID;
  50085. }
  50086. }
  50087. }
  50088. else {
  50089. this._currentFrameCounter++;
  50090. }
  50091. };
  50092. /**
  50093. * Copy the properties of particle to another one.
  50094. * @param other the particle to copy the information to.
  50095. */
  50096. Particle.prototype.copyTo = function (other) {
  50097. other.position.copyFrom(this.position);
  50098. other.direction.copyFrom(this.direction);
  50099. other.color.copyFrom(this.color);
  50100. other.colorStep.copyFrom(this.colorStep);
  50101. other.lifeTime = this.lifeTime;
  50102. other.age = this.age;
  50103. other.size = this.size;
  50104. other.angle = this.angle;
  50105. other.angularSpeed = this.angularSpeed;
  50106. other.particleSystem = this.particleSystem;
  50107. other.cellIndex = this.cellIndex;
  50108. };
  50109. return Particle;
  50110. }());
  50111. BABYLON.Particle = Particle;
  50112. })(BABYLON || (BABYLON = {}));
  50113. //# sourceMappingURL=babylon.particle.js.map
  50114. var BABYLON;
  50115. (function (BABYLON) {
  50116. /**
  50117. * This represents a particle system in Babylon.
  50118. * 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.
  50119. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50120. * @example https://doc.babylonjs.com/babylon101/particles
  50121. */
  50122. var ParticleSystem = /** @class */ (function () {
  50123. /**
  50124. * Instantiates a particle system.
  50125. * 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.
  50126. * @param name The name of the particle system
  50127. * @param capacity The max number of particles alive at the same time
  50128. * @param scene The scene the particle system belongs to
  50129. * @param customEffect a custom effect used to change the way particles are rendered by default
  50130. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50131. * @param epsilon Offset used to render the particles
  50132. */
  50133. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50134. if (customEffect === void 0) { customEffect = null; }
  50135. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50136. if (epsilon === void 0) { epsilon = 0.01; }
  50137. var _this = this;
  50138. /**
  50139. * List of animations used by the particle system.
  50140. */
  50141. this.animations = [];
  50142. /**
  50143. * The rendering group used by the Particle system to chose when to render.
  50144. */
  50145. this.renderingGroupId = 0;
  50146. /**
  50147. * The emitter represents the Mesh or position we are attaching the particle system to.
  50148. */
  50149. this.emitter = null;
  50150. /**
  50151. * The maximum number of particles to emit per frame
  50152. */
  50153. this.emitRate = 10;
  50154. /**
  50155. * If you want to launch only a few particles at once, that can be done, as well.
  50156. */
  50157. this.manualEmitCount = -1;
  50158. /**
  50159. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50160. */
  50161. this.updateSpeed = 0.01;
  50162. /**
  50163. * The amount of time the particle system is running (depends of the overall update speed).
  50164. */
  50165. this.targetStopDuration = 0;
  50166. /**
  50167. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50168. */
  50169. this.disposeOnStop = false;
  50170. /**
  50171. * Minimum power of emitting particles.
  50172. */
  50173. this.minEmitPower = 1;
  50174. /**
  50175. * Maximum power of emitting particles.
  50176. */
  50177. this.maxEmitPower = 1;
  50178. /**
  50179. * Minimum life time of emitting particles.
  50180. */
  50181. this.minLifeTime = 1;
  50182. /**
  50183. * Maximum life time of emitting particles.
  50184. */
  50185. this.maxLifeTime = 1;
  50186. /**
  50187. * Minimum Size of emitting particles.
  50188. */
  50189. this.minSize = 1;
  50190. /**
  50191. * Maximum Size of emitting particles.
  50192. */
  50193. this.maxSize = 1;
  50194. /**
  50195. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50196. */
  50197. this.minAngularSpeed = 0;
  50198. /**
  50199. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50200. */
  50201. this.maxAngularSpeed = 0;
  50202. /**
  50203. * The layer mask we are rendering the particles through.
  50204. */
  50205. this.layerMask = 0x0FFFFFFF;
  50206. /**
  50207. * This can help using your own shader to render the particle system.
  50208. * The according effect will be created
  50209. */
  50210. this.customShader = null;
  50211. /**
  50212. * By default particle system starts as soon as they are created. This prevents the
  50213. * automatic start to happen and let you decide when to start emitting particles.
  50214. */
  50215. this.preventAutoStart = false;
  50216. /**
  50217. * Callback triggered when the particle animation is ending.
  50218. */
  50219. this.onAnimationEnd = null;
  50220. /**
  50221. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50222. */
  50223. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50224. /**
  50225. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50226. * to override the particles.
  50227. */
  50228. this.forceDepthWrite = false;
  50229. /**
  50230. * You can use gravity if you want to give an orientation to your particles.
  50231. */
  50232. this.gravity = BABYLON.Vector3.Zero();
  50233. /**
  50234. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50235. */
  50236. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50237. /**
  50238. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50239. */
  50240. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50241. /**
  50242. * Color the particle will have at the end of its lifetime.
  50243. */
  50244. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50245. /**
  50246. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50247. */
  50248. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50249. /**
  50250. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50251. */
  50252. this.spriteCellLoop = true;
  50253. /**
  50254. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50255. */
  50256. this.spriteCellChangeSpeed = 0;
  50257. /**
  50258. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50259. */
  50260. this.startSpriteCellID = 0;
  50261. /**
  50262. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50263. */
  50264. this.endSpriteCellID = 0;
  50265. /**
  50266. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50267. */
  50268. this.spriteCellWidth = 0;
  50269. /**
  50270. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50271. */
  50272. this.spriteCellHeight = 0;
  50273. /**
  50274. * An event triggered when the system is disposed.
  50275. */
  50276. this.onDisposeObservable = new BABYLON.Observable();
  50277. this._particles = new Array();
  50278. this._stockParticles = new Array();
  50279. this._newPartsExcess = 0;
  50280. this._vertexBuffers = {};
  50281. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50282. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50283. this._scaledDirection = BABYLON.Vector3.Zero();
  50284. this._scaledGravity = BABYLON.Vector3.Zero();
  50285. this._currentRenderId = -1;
  50286. this._started = false;
  50287. this._stopped = false;
  50288. this._actualFrame = 0;
  50289. this._vertexBufferSize = 11;
  50290. this._appendParticleVertexes = null;
  50291. this.id = name;
  50292. this.name = name;
  50293. this._capacity = capacity;
  50294. this._epsilon = epsilon;
  50295. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50296. if (isAnimationSheetEnabled) {
  50297. this._vertexBufferSize = 12;
  50298. }
  50299. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50300. this._customEffect = customEffect;
  50301. scene.particleSystems.push(this);
  50302. this._createIndexBuffer();
  50303. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50304. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50305. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50306. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50307. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50308. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50309. if (this._isAnimationSheetEnabled) {
  50310. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50311. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50312. }
  50313. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50314. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50315. this._vertexBuffers["options"] = options;
  50316. // Default emitter type
  50317. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50318. this.updateFunction = function (particles) {
  50319. for (var index = 0; index < particles.length; index++) {
  50320. var particle = particles[index];
  50321. particle.age += _this._scaledUpdateSpeed;
  50322. if (particle.age >= particle.lifeTime) {
  50323. _this.recycleParticle(particle);
  50324. index--;
  50325. continue;
  50326. }
  50327. else {
  50328. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50329. particle.color.addInPlace(_this._scaledColorStep);
  50330. if (particle.color.a < 0)
  50331. particle.color.a = 0;
  50332. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50333. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50334. particle.position.addInPlace(_this._scaledDirection);
  50335. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50336. particle.direction.addInPlace(_this._scaledGravity);
  50337. if (_this._isAnimationSheetEnabled) {
  50338. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50339. }
  50340. }
  50341. }
  50342. };
  50343. }
  50344. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  50345. /**
  50346. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50347. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50348. */
  50349. get: function () {
  50350. if (this.particleEmitterType.direction1) {
  50351. return this.particleEmitterType.direction1;
  50352. }
  50353. return BABYLON.Vector3.Zero();
  50354. },
  50355. set: function (value) {
  50356. if (this.particleEmitterType.direction1) {
  50357. this.particleEmitterType.direction1 = value;
  50358. }
  50359. },
  50360. enumerable: true,
  50361. configurable: true
  50362. });
  50363. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  50364. /**
  50365. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50366. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50367. */
  50368. get: function () {
  50369. if (this.particleEmitterType.direction2) {
  50370. return this.particleEmitterType.direction2;
  50371. }
  50372. return BABYLON.Vector3.Zero();
  50373. },
  50374. set: function (value) {
  50375. if (this.particleEmitterType.direction2) {
  50376. this.particleEmitterType.direction2 = value;
  50377. }
  50378. },
  50379. enumerable: true,
  50380. configurable: true
  50381. });
  50382. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  50383. /**
  50384. * 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.
  50385. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50386. */
  50387. get: function () {
  50388. if (this.particleEmitterType.minEmitBox) {
  50389. return this.particleEmitterType.minEmitBox;
  50390. }
  50391. return BABYLON.Vector3.Zero();
  50392. },
  50393. set: function (value) {
  50394. if (this.particleEmitterType.minEmitBox) {
  50395. this.particleEmitterType.minEmitBox = value;
  50396. }
  50397. },
  50398. enumerable: true,
  50399. configurable: true
  50400. });
  50401. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  50402. /**
  50403. * 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.
  50404. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50405. */
  50406. get: function () {
  50407. if (this.particleEmitterType.maxEmitBox) {
  50408. return this.particleEmitterType.maxEmitBox;
  50409. }
  50410. return BABYLON.Vector3.Zero();
  50411. },
  50412. set: function (value) {
  50413. if (this.particleEmitterType.maxEmitBox) {
  50414. this.particleEmitterType.maxEmitBox = value;
  50415. }
  50416. },
  50417. enumerable: true,
  50418. configurable: true
  50419. });
  50420. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50421. /**
  50422. * Sets a callback that will be triggered when the system is disposed.
  50423. */
  50424. set: function (callback) {
  50425. if (this._onDisposeObserver) {
  50426. this.onDisposeObservable.remove(this._onDisposeObserver);
  50427. }
  50428. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50429. },
  50430. enumerable: true,
  50431. configurable: true
  50432. });
  50433. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50434. /**
  50435. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50436. */
  50437. get: function () {
  50438. return this._isAnimationSheetEnabled;
  50439. },
  50440. enumerable: true,
  50441. configurable: true
  50442. });
  50443. /**
  50444. * Returns the string "ParticleSystem"
  50445. * @returns a string containing the class name
  50446. */
  50447. ParticleSystem.prototype.getClassName = function () {
  50448. return "ParticleSystem";
  50449. };
  50450. ParticleSystem.prototype._createIndexBuffer = function () {
  50451. var indices = [];
  50452. var index = 0;
  50453. for (var count = 0; count < this._capacity; count++) {
  50454. indices.push(index);
  50455. indices.push(index + 1);
  50456. indices.push(index + 2);
  50457. indices.push(index);
  50458. indices.push(index + 2);
  50459. indices.push(index + 3);
  50460. index += 4;
  50461. }
  50462. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50463. };
  50464. /**
  50465. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50466. * Its lifetime will start back at 0.
  50467. * @param particle The particle to recycle
  50468. */
  50469. ParticleSystem.prototype.recycleParticle = function (particle) {
  50470. var lastParticle = this._particles.pop();
  50471. if (lastParticle !== particle) {
  50472. lastParticle.copyTo(particle);
  50473. this._stockParticles.push(lastParticle);
  50474. }
  50475. };
  50476. /**
  50477. * Gets the maximum number of particles active at the same time.
  50478. * @returns The max number of active particles.
  50479. */
  50480. ParticleSystem.prototype.getCapacity = function () {
  50481. return this._capacity;
  50482. };
  50483. /**
  50484. * Gets Wether there are still active particles in the system.
  50485. * @returns True if it is alive, otherwise false.
  50486. */
  50487. ParticleSystem.prototype.isAlive = function () {
  50488. return this._alive;
  50489. };
  50490. /**
  50491. * Gets Wether the system has been started.
  50492. * @returns True if it has been started, otherwise false.
  50493. */
  50494. ParticleSystem.prototype.isStarted = function () {
  50495. return this._started;
  50496. };
  50497. /**
  50498. * Starts the particle system and begins to emit.
  50499. */
  50500. ParticleSystem.prototype.start = function () {
  50501. this._started = true;
  50502. this._stopped = false;
  50503. this._actualFrame = 0;
  50504. };
  50505. /**
  50506. * Stops the particle system.
  50507. */
  50508. ParticleSystem.prototype.stop = function () {
  50509. this._stopped = true;
  50510. };
  50511. /**
  50512. * Remove all active particles
  50513. */
  50514. ParticleSystem.prototype.reset = function () {
  50515. this._stockParticles = [];
  50516. this._particles = [];
  50517. };
  50518. /**
  50519. * @ignore (for internal use only)
  50520. */
  50521. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50522. var offset = index * this._vertexBufferSize;
  50523. this._vertexData[offset] = particle.position.x;
  50524. this._vertexData[offset + 1] = particle.position.y;
  50525. this._vertexData[offset + 2] = particle.position.z;
  50526. this._vertexData[offset + 3] = particle.color.r;
  50527. this._vertexData[offset + 4] = particle.color.g;
  50528. this._vertexData[offset + 5] = particle.color.b;
  50529. this._vertexData[offset + 6] = particle.color.a;
  50530. this._vertexData[offset + 7] = particle.angle;
  50531. this._vertexData[offset + 8] = particle.size;
  50532. this._vertexData[offset + 9] = offsetX;
  50533. this._vertexData[offset + 10] = offsetY;
  50534. };
  50535. /**
  50536. * @ignore (for internal use only)
  50537. */
  50538. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50539. if (offsetX === 0)
  50540. offsetX = this._epsilon;
  50541. else if (offsetX === 1)
  50542. offsetX = 1 - this._epsilon;
  50543. if (offsetY === 0)
  50544. offsetY = this._epsilon;
  50545. else if (offsetY === 1)
  50546. offsetY = 1 - this._epsilon;
  50547. var offset = index * this._vertexBufferSize;
  50548. this._vertexData[offset] = particle.position.x;
  50549. this._vertexData[offset + 1] = particle.position.y;
  50550. this._vertexData[offset + 2] = particle.position.z;
  50551. this._vertexData[offset + 3] = particle.color.r;
  50552. this._vertexData[offset + 4] = particle.color.g;
  50553. this._vertexData[offset + 5] = particle.color.b;
  50554. this._vertexData[offset + 6] = particle.color.a;
  50555. this._vertexData[offset + 7] = particle.angle;
  50556. this._vertexData[offset + 8] = particle.size;
  50557. this._vertexData[offset + 9] = offsetX;
  50558. this._vertexData[offset + 10] = offsetY;
  50559. this._vertexData[offset + 11] = particle.cellIndex;
  50560. };
  50561. ParticleSystem.prototype._update = function (newParticles) {
  50562. // Update current
  50563. this._alive = this._particles.length > 0;
  50564. this.updateFunction(this._particles);
  50565. // Add new ones
  50566. var worldMatrix;
  50567. if (this.emitter.position) {
  50568. var emitterMesh = this.emitter;
  50569. worldMatrix = emitterMesh.getWorldMatrix();
  50570. }
  50571. else {
  50572. var emitterPosition = this.emitter;
  50573. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50574. }
  50575. var particle;
  50576. for (var index = 0; index < newParticles; index++) {
  50577. if (this._particles.length === this._capacity) {
  50578. break;
  50579. }
  50580. if (this._stockParticles.length !== 0) {
  50581. particle = this._stockParticles.pop();
  50582. particle.age = 0;
  50583. particle.cellIndex = this.startSpriteCellID;
  50584. }
  50585. else {
  50586. particle = new BABYLON.Particle(this);
  50587. }
  50588. this._particles.push(particle);
  50589. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50590. if (this.startPositionFunction) {
  50591. this.startPositionFunction(worldMatrix, particle.position, particle);
  50592. }
  50593. else {
  50594. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50595. }
  50596. if (this.startDirectionFunction) {
  50597. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50598. }
  50599. else {
  50600. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50601. }
  50602. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50603. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50604. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50605. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50606. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50607. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50608. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50609. }
  50610. };
  50611. ParticleSystem.prototype._getEffect = function () {
  50612. if (this._customEffect) {
  50613. return this._customEffect;
  50614. }
  50615. ;
  50616. var defines = [];
  50617. if (this._scene.clipPlane) {
  50618. defines.push("#define CLIPPLANE");
  50619. }
  50620. if (this._isAnimationSheetEnabled) {
  50621. defines.push("#define ANIMATESHEET");
  50622. }
  50623. // Effect
  50624. var join = defines.join("\n");
  50625. if (this._cachedDefines !== join) {
  50626. this._cachedDefines = join;
  50627. var attributesNamesOrOptions;
  50628. var effectCreationOption;
  50629. if (this._isAnimationSheetEnabled) {
  50630. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50631. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50632. }
  50633. else {
  50634. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50635. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50636. }
  50637. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50638. }
  50639. return this._effect;
  50640. };
  50641. /**
  50642. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50643. */
  50644. ParticleSystem.prototype.animate = function () {
  50645. if (!this._started)
  50646. return;
  50647. var effect = this._getEffect();
  50648. // Check
  50649. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50650. return;
  50651. if (this._currentRenderId === this._scene.getRenderId()) {
  50652. return;
  50653. }
  50654. this._currentRenderId = this._scene.getRenderId();
  50655. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50656. // determine the number of particles we need to create
  50657. var newParticles;
  50658. if (this.manualEmitCount > -1) {
  50659. newParticles = this.manualEmitCount;
  50660. this._newPartsExcess = 0;
  50661. this.manualEmitCount = 0;
  50662. }
  50663. else {
  50664. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50665. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50666. }
  50667. if (this._newPartsExcess > 1.0) {
  50668. newParticles += this._newPartsExcess >> 0;
  50669. this._newPartsExcess -= this._newPartsExcess >> 0;
  50670. }
  50671. this._alive = false;
  50672. if (!this._stopped) {
  50673. this._actualFrame += this._scaledUpdateSpeed;
  50674. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  50675. this.stop();
  50676. }
  50677. else {
  50678. newParticles = 0;
  50679. }
  50680. this._update(newParticles);
  50681. // Stopped?
  50682. if (this._stopped) {
  50683. if (!this._alive) {
  50684. this._started = false;
  50685. if (this.onAnimationEnd) {
  50686. this.onAnimationEnd();
  50687. }
  50688. if (this.disposeOnStop) {
  50689. this._scene._toBeDisposed.push(this);
  50690. }
  50691. }
  50692. }
  50693. // Animation sheet
  50694. if (this._isAnimationSheetEnabled) {
  50695. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  50696. }
  50697. else {
  50698. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  50699. }
  50700. // Update VBO
  50701. var offset = 0;
  50702. for (var index = 0; index < this._particles.length; index++) {
  50703. var particle = this._particles[index];
  50704. this._appendParticleVertexes(offset, particle);
  50705. offset += 4;
  50706. }
  50707. if (this._vertexBuffer) {
  50708. this._vertexBuffer.update(this._vertexData);
  50709. }
  50710. };
  50711. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  50712. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  50713. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  50714. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  50715. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  50716. };
  50717. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  50718. this._appendParticleVertex(offset++, particle, 0, 0);
  50719. this._appendParticleVertex(offset++, particle, 1, 0);
  50720. this._appendParticleVertex(offset++, particle, 1, 1);
  50721. this._appendParticleVertex(offset++, particle, 0, 1);
  50722. };
  50723. /**
  50724. * Rebuilds the particle system.
  50725. */
  50726. ParticleSystem.prototype.rebuild = function () {
  50727. this._createIndexBuffer();
  50728. if (this._vertexBuffer) {
  50729. this._vertexBuffer._rebuild();
  50730. }
  50731. };
  50732. /**
  50733. * Renders the particle system in its current state.
  50734. * @returns the current number of particles
  50735. */
  50736. ParticleSystem.prototype.render = function () {
  50737. var effect = this._getEffect();
  50738. // Check
  50739. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  50740. return 0;
  50741. }
  50742. var engine = this._scene.getEngine();
  50743. // Render
  50744. engine.enableEffect(effect);
  50745. engine.setState(false);
  50746. var viewMatrix = this._scene.getViewMatrix();
  50747. effect.setTexture("diffuseSampler", this.particleTexture);
  50748. effect.setMatrix("view", viewMatrix);
  50749. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50750. if (this._isAnimationSheetEnabled) {
  50751. var baseSize = this.particleTexture.getBaseSize();
  50752. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  50753. }
  50754. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  50755. if (this._scene.clipPlane) {
  50756. var clipPlane = this._scene.clipPlane;
  50757. var invView = viewMatrix.clone();
  50758. invView.invert();
  50759. effect.setMatrix("invView", invView);
  50760. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  50761. }
  50762. // VBOs
  50763. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50764. // Draw order
  50765. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  50766. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  50767. }
  50768. else {
  50769. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50770. }
  50771. if (this.forceDepthWrite) {
  50772. engine.setDepthWrite(true);
  50773. }
  50774. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  50775. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50776. return this._particles.length;
  50777. };
  50778. /**
  50779. * Disposes the particle system and free the associated resources.
  50780. */
  50781. ParticleSystem.prototype.dispose = function () {
  50782. if (this._vertexBuffer) {
  50783. this._vertexBuffer.dispose();
  50784. this._vertexBuffer = null;
  50785. }
  50786. if (this._indexBuffer) {
  50787. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50788. this._indexBuffer = null;
  50789. }
  50790. if (this.particleTexture) {
  50791. this.particleTexture.dispose();
  50792. this.particleTexture = null;
  50793. }
  50794. // Remove from scene
  50795. var index = this._scene.particleSystems.indexOf(this);
  50796. if (index > -1) {
  50797. this._scene.particleSystems.splice(index, 1);
  50798. }
  50799. // Callback
  50800. this.onDisposeObservable.notifyObservers(this);
  50801. this.onDisposeObservable.clear();
  50802. };
  50803. /**
  50804. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  50805. * @param radius The radius of the sphere to emit from
  50806. * @returns the emitter
  50807. */
  50808. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  50809. if (radius === void 0) { radius = 1; }
  50810. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  50811. this.particleEmitterType = particleEmitter;
  50812. return particleEmitter;
  50813. };
  50814. /**
  50815. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  50816. * @param radius The radius of the sphere to emit from
  50817. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  50818. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  50819. * @returns the emitter
  50820. */
  50821. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  50822. if (radius === void 0) { radius = 1; }
  50823. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  50824. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  50825. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  50826. this.particleEmitterType = particleEmitter;
  50827. return particleEmitter;
  50828. };
  50829. /**
  50830. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  50831. * @param radius The radius of the cone to emit from
  50832. * @param angle The base angle of the cone
  50833. * @returns the emitter
  50834. */
  50835. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  50836. if (radius === void 0) { radius = 1; }
  50837. if (angle === void 0) { angle = Math.PI / 4; }
  50838. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  50839. this.particleEmitterType = particleEmitter;
  50840. return particleEmitter;
  50841. };
  50842. // 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.
  50843. /**
  50844. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  50845. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  50846. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  50847. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50848. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50849. * @returns the emitter
  50850. */
  50851. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  50852. var particleEmitter = new BABYLON.BoxParticleEmitter();
  50853. this.direction1 = direction1;
  50854. this.direction2 = direction2;
  50855. this.minEmitBox = minEmitBox;
  50856. this.maxEmitBox = maxEmitBox;
  50857. this.particleEmitterType = particleEmitter;
  50858. return particleEmitter;
  50859. };
  50860. /**
  50861. * Clones the particle system.
  50862. * @param name The name of the cloned object
  50863. * @param newEmitter The new emitter to use
  50864. * @returns the cloned particle system
  50865. */
  50866. ParticleSystem.prototype.clone = function (name, newEmitter) {
  50867. var custom = null;
  50868. var program = null;
  50869. if (this.customShader != null) {
  50870. program = this.customShader;
  50871. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50872. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50873. }
  50874. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  50875. result.customShader = program;
  50876. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  50877. if (newEmitter === undefined) {
  50878. newEmitter = this.emitter;
  50879. }
  50880. result.emitter = newEmitter;
  50881. if (this.particleTexture) {
  50882. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  50883. }
  50884. if (!this.preventAutoStart) {
  50885. result.start();
  50886. }
  50887. return result;
  50888. };
  50889. /**
  50890. * Serializes the particle system to a JSON object.
  50891. * @returns the JSON object
  50892. */
  50893. ParticleSystem.prototype.serialize = function () {
  50894. var serializationObject = {};
  50895. serializationObject.name = this.name;
  50896. serializationObject.id = this.id;
  50897. // Emitter
  50898. if (this.emitter.position) {
  50899. var emitterMesh = this.emitter;
  50900. serializationObject.emitterId = emitterMesh.id;
  50901. }
  50902. else {
  50903. var emitterPosition = this.emitter;
  50904. serializationObject.emitter = emitterPosition.asArray();
  50905. }
  50906. serializationObject.capacity = this.getCapacity();
  50907. if (this.particleTexture) {
  50908. serializationObject.textureName = this.particleTexture.name;
  50909. }
  50910. // Animations
  50911. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  50912. // Particle system
  50913. serializationObject.minAngularSpeed = this.minAngularSpeed;
  50914. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  50915. serializationObject.minSize = this.minSize;
  50916. serializationObject.maxSize = this.maxSize;
  50917. serializationObject.minEmitPower = this.minEmitPower;
  50918. serializationObject.maxEmitPower = this.maxEmitPower;
  50919. serializationObject.minLifeTime = this.minLifeTime;
  50920. serializationObject.maxLifeTime = this.maxLifeTime;
  50921. serializationObject.emitRate = this.emitRate;
  50922. serializationObject.minEmitBox = this.minEmitBox.asArray();
  50923. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  50924. serializationObject.gravity = this.gravity.asArray();
  50925. serializationObject.direction1 = this.direction1.asArray();
  50926. serializationObject.direction2 = this.direction2.asArray();
  50927. serializationObject.color1 = this.color1.asArray();
  50928. serializationObject.color2 = this.color2.asArray();
  50929. serializationObject.colorDead = this.colorDead.asArray();
  50930. serializationObject.updateSpeed = this.updateSpeed;
  50931. serializationObject.targetStopDuration = this.targetStopDuration;
  50932. serializationObject.textureMask = this.textureMask.asArray();
  50933. serializationObject.blendMode = this.blendMode;
  50934. serializationObject.customShader = this.customShader;
  50935. serializationObject.preventAutoStart = this.preventAutoStart;
  50936. serializationObject.startSpriteCellID = this.startSpriteCellID;
  50937. serializationObject.endSpriteCellID = this.endSpriteCellID;
  50938. serializationObject.spriteCellLoop = this.spriteCellLoop;
  50939. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  50940. serializationObject.spriteCellWidth = this.spriteCellWidth;
  50941. serializationObject.spriteCellHeight = this.spriteCellHeight;
  50942. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  50943. // Emitter
  50944. if (this.particleEmitterType) {
  50945. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  50946. }
  50947. return serializationObject;
  50948. };
  50949. /**
  50950. * Parses a JSON object to create a particle system.
  50951. * @param parsedParticleSystem The JSON object to parse
  50952. * @param scene The scene to create the particle system in
  50953. * @param rootUrl The root url to use to load external dependencies like texture
  50954. * @returns the Parsed particle system
  50955. */
  50956. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  50957. var name = parsedParticleSystem.name;
  50958. var custom = null;
  50959. var program = null;
  50960. if (parsedParticleSystem.customShader) {
  50961. program = parsedParticleSystem.customShader;
  50962. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50963. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50964. }
  50965. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  50966. particleSystem.customShader = program;
  50967. if (parsedParticleSystem.id) {
  50968. particleSystem.id = parsedParticleSystem.id;
  50969. }
  50970. // Auto start
  50971. if (parsedParticleSystem.preventAutoStart) {
  50972. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  50973. }
  50974. // Texture
  50975. if (parsedParticleSystem.textureName) {
  50976. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  50977. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  50978. }
  50979. // Emitter
  50980. if (parsedParticleSystem.emitterId) {
  50981. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  50982. }
  50983. else {
  50984. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  50985. }
  50986. // Animations
  50987. if (parsedParticleSystem.animations) {
  50988. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  50989. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  50990. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50991. }
  50992. }
  50993. if (parsedParticleSystem.autoAnimate) {
  50994. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  50995. }
  50996. // Particle system
  50997. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  50998. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  50999. particleSystem.minSize = parsedParticleSystem.minSize;
  51000. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51001. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51002. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51003. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51004. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51005. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51006. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51007. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51008. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51009. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51010. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51011. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51012. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51013. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51014. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51015. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51016. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51017. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51018. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51019. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51020. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51021. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51022. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51023. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51024. if (!particleSystem.preventAutoStart) {
  51025. particleSystem.start();
  51026. }
  51027. return particleSystem;
  51028. };
  51029. /**
  51030. * Source color is added to the destination color without alpha affecting the result.
  51031. */
  51032. ParticleSystem.BLENDMODE_ONEONE = 0;
  51033. /**
  51034. * Blend current color and particle color using particle’s alpha.
  51035. */
  51036. ParticleSystem.BLENDMODE_STANDARD = 1;
  51037. return ParticleSystem;
  51038. }());
  51039. BABYLON.ParticleSystem = ParticleSystem;
  51040. })(BABYLON || (BABYLON = {}));
  51041. //# sourceMappingURL=babylon.particleSystem.js.map
  51042. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51043. var BABYLON;
  51044. (function (BABYLON) {
  51045. /**
  51046. * Particle emitter emitting particles from the inside of a box.
  51047. * It emits the particles randomly between 2 given directions.
  51048. */
  51049. var BoxParticleEmitter = /** @class */ (function () {
  51050. /**
  51051. * Creates a new instance of @see BoxParticleEmitter
  51052. */
  51053. function BoxParticleEmitter() {
  51054. /**
  51055. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51056. */
  51057. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51058. /**
  51059. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51060. */
  51061. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51062. /**
  51063. * 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.
  51064. */
  51065. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51066. /**
  51067. * 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.
  51068. */
  51069. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51070. }
  51071. /**
  51072. * Called by the particle System when the direction is computed for the created particle.
  51073. * @param emitPower is the power of the particle (speed)
  51074. * @param worldMatrix is the world matrix of the particle system
  51075. * @param directionToUpdate is the direction vector to update with the result
  51076. * @param particle is the particle we are computed the direction for
  51077. */
  51078. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51079. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51080. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51081. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51082. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51083. };
  51084. /**
  51085. * Called by the particle System when the position is computed for the created particle.
  51086. * @param worldMatrix is the world matrix of the particle system
  51087. * @param positionToUpdate is the position vector to update with the result
  51088. * @param particle is the particle we are computed the position for
  51089. */
  51090. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51091. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51092. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51093. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51094. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51095. };
  51096. /**
  51097. * Clones the current emitter and returns a copy of it
  51098. * @returns the new emitter
  51099. */
  51100. BoxParticleEmitter.prototype.clone = function () {
  51101. var newOne = new BoxParticleEmitter();
  51102. BABYLON.Tools.DeepCopy(this, newOne);
  51103. return newOne;
  51104. };
  51105. /**
  51106. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51107. * @param effect defines the update shader
  51108. */
  51109. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51110. effect.setVector3("direction1", this.direction1);
  51111. effect.setVector3("direction2", this.direction2);
  51112. effect.setVector3("minEmitBox", this.minEmitBox);
  51113. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51114. };
  51115. /**
  51116. * Returns a string to use to update the GPU particles update shader
  51117. * @returns a string containng the defines string
  51118. */
  51119. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51120. return "#define BOXEMITTER";
  51121. };
  51122. /**
  51123. * Returns the string "BoxEmitter"
  51124. * @returns a string containing the class name
  51125. */
  51126. BoxParticleEmitter.prototype.getClassName = function () {
  51127. return "BoxEmitter";
  51128. };
  51129. /**
  51130. * Serializes the particle system to a JSON object.
  51131. * @returns the JSON object
  51132. */
  51133. BoxParticleEmitter.prototype.serialize = function () {
  51134. var serializationObject = {};
  51135. serializationObject.type = this.getClassName();
  51136. serializationObject.direction1 = this.direction1.asArray();
  51137. ;
  51138. serializationObject.direction2 = this.direction2.asArray();
  51139. ;
  51140. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51141. ;
  51142. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51143. ;
  51144. return serializationObject;
  51145. };
  51146. /**
  51147. * Parse properties from a JSON object
  51148. * @param serializationObject defines the JSON object
  51149. */
  51150. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51151. this.direction1.copyFrom(serializationObject.direction1);
  51152. this.direction2.copyFrom(serializationObject.direction2);
  51153. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51154. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51155. };
  51156. return BoxParticleEmitter;
  51157. }());
  51158. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51159. })(BABYLON || (BABYLON = {}));
  51160. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51161. var BABYLON;
  51162. (function (BABYLON) {
  51163. /**
  51164. * Particle emitter emitting particles from the inside of a cone.
  51165. * It emits the particles alongside the cone volume from the base to the particle.
  51166. * The emission direction might be randomized.
  51167. */
  51168. var ConeParticleEmitter = /** @class */ (function () {
  51169. /**
  51170. * Creates a new instance of @see ConeParticleEmitter
  51171. * @param radius the radius of the emission cone (1 by default)
  51172. * @param angles the cone base angle (PI by default)
  51173. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51174. */
  51175. function ConeParticleEmitter(radius,
  51176. /**
  51177. * The radius of the emission cone.
  51178. */
  51179. angle,
  51180. /**
  51181. * The cone base angle.
  51182. */
  51183. directionRandomizer) {
  51184. if (radius === void 0) { radius = 1; }
  51185. if (angle === void 0) { angle = Math.PI; }
  51186. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51187. this.angle = angle;
  51188. this.directionRandomizer = directionRandomizer;
  51189. this.radius = radius;
  51190. }
  51191. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51192. /**
  51193. * Gets the radius of the emission cone.
  51194. */
  51195. get: function () {
  51196. return this._radius;
  51197. },
  51198. /**
  51199. * Sets the radius of the emission cone.
  51200. */
  51201. set: function (value) {
  51202. this._radius = value;
  51203. if (this.angle !== 0) {
  51204. this._height = value / Math.tan(this.angle / 2);
  51205. }
  51206. else {
  51207. this._height = 1;
  51208. }
  51209. },
  51210. enumerable: true,
  51211. configurable: true
  51212. });
  51213. /**
  51214. * Called by the particle System when the direction is computed for the created particle.
  51215. * @param emitPower is the power of the particle (speed)
  51216. * @param worldMatrix is the world matrix of the particle system
  51217. * @param directionToUpdate is the direction vector to update with the result
  51218. * @param particle is the particle we are computed the direction for
  51219. */
  51220. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51221. if (this.angle === 0) {
  51222. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51223. }
  51224. else {
  51225. // measure the direction Vector from the emitter to the particle.
  51226. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51227. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51228. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51229. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51230. direction.x += randX;
  51231. direction.y += randY;
  51232. direction.z += randZ;
  51233. direction.normalize();
  51234. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51235. }
  51236. };
  51237. /**
  51238. * Called by the particle System when the position is computed for the created particle.
  51239. * @param worldMatrix is the world matrix of the particle system
  51240. * @param positionToUpdate is the position vector to update with the result
  51241. * @param particle is the particle we are computed the position for
  51242. */
  51243. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51244. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51245. var h = BABYLON.Scalar.RandomRange(0, 1);
  51246. // Better distribution in a cone at normal angles.
  51247. h = 1 - h * h;
  51248. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51249. radius = radius * h / this._height;
  51250. var randX = radius * Math.sin(s);
  51251. var randZ = radius * Math.cos(s);
  51252. var randY = h * this._height;
  51253. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51254. };
  51255. /**
  51256. * Clones the current emitter and returns a copy of it
  51257. * @returns the new emitter
  51258. */
  51259. ConeParticleEmitter.prototype.clone = function () {
  51260. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51261. BABYLON.Tools.DeepCopy(this, newOne);
  51262. return newOne;
  51263. };
  51264. /**
  51265. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51266. * @param effect defines the update shader
  51267. */
  51268. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51269. effect.setFloat("radius", this.radius);
  51270. effect.setFloat("angle", this.angle);
  51271. effect.setFloat("height", this._height);
  51272. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51273. };
  51274. /**
  51275. * Returns a string to use to update the GPU particles update shader
  51276. * @returns a string containng the defines string
  51277. */
  51278. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51279. return "#define CONEEMITTER";
  51280. };
  51281. /**
  51282. * Returns the string "BoxEmitter"
  51283. * @returns a string containing the class name
  51284. */
  51285. ConeParticleEmitter.prototype.getClassName = function () {
  51286. return "ConeEmitter";
  51287. };
  51288. /**
  51289. * Serializes the particle system to a JSON object.
  51290. * @returns the JSON object
  51291. */
  51292. ConeParticleEmitter.prototype.serialize = function () {
  51293. var serializationObject = {};
  51294. serializationObject.type = this.getClassName();
  51295. serializationObject.radius = this.radius;
  51296. serializationObject.angle = this.angle;
  51297. serializationObject.directionRandomizer = this.directionRandomizer;
  51298. return serializationObject;
  51299. };
  51300. /**
  51301. * Parse properties from a JSON object
  51302. * @param serializationObject defines the JSON object
  51303. */
  51304. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  51305. this.radius = serializationObject.radius;
  51306. this.angle = serializationObject.angle;
  51307. this.directionRandomizer = serializationObject.directionRandomizer;
  51308. };
  51309. return ConeParticleEmitter;
  51310. }());
  51311. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51312. })(BABYLON || (BABYLON = {}));
  51313. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51314. var BABYLON;
  51315. (function (BABYLON) {
  51316. /**
  51317. * Particle emitter emitting particles from the inside of a sphere.
  51318. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51319. */
  51320. var SphereParticleEmitter = /** @class */ (function () {
  51321. /**
  51322. * Creates a new instance of @see SphereParticleEmitter
  51323. * @param radius the radius of the emission sphere (1 by default)
  51324. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51325. */
  51326. function SphereParticleEmitter(
  51327. /**
  51328. * The radius of the emission sphere.
  51329. */
  51330. radius,
  51331. /**
  51332. * How much to randomize the particle direction [0-1].
  51333. */
  51334. directionRandomizer) {
  51335. if (radius === void 0) { radius = 1; }
  51336. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51337. this.radius = radius;
  51338. this.directionRandomizer = directionRandomizer;
  51339. }
  51340. /**
  51341. * Called by the particle System when the direction is computed for the created particle.
  51342. * @param emitPower is the power of the particle (speed)
  51343. * @param worldMatrix is the world matrix of the particle system
  51344. * @param directionToUpdate is the direction vector to update with the result
  51345. * @param particle is the particle we are computed the direction for
  51346. */
  51347. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51348. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51349. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51350. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51351. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51352. direction.x += randX;
  51353. direction.y += randY;
  51354. direction.z += randZ;
  51355. direction.normalize();
  51356. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51357. };
  51358. /**
  51359. * Called by the particle System when the position is computed for the created particle.
  51360. * @param worldMatrix is the world matrix of the particle system
  51361. * @param positionToUpdate is the position vector to update with the result
  51362. * @param particle is the particle we are computed the position for
  51363. */
  51364. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51365. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51366. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51367. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  51368. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  51369. var randY = randRadius * Math.cos(theta);
  51370. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  51371. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51372. };
  51373. /**
  51374. * Clones the current emitter and returns a copy of it
  51375. * @returns the new emitter
  51376. */
  51377. SphereParticleEmitter.prototype.clone = function () {
  51378. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51379. BABYLON.Tools.DeepCopy(this, newOne);
  51380. return newOne;
  51381. };
  51382. /**
  51383. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51384. * @param effect defines the update shader
  51385. */
  51386. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  51387. effect.setFloat("radius", this.radius);
  51388. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51389. };
  51390. /**
  51391. * Returns a string to use to update the GPU particles update shader
  51392. * @returns a string containng the defines string
  51393. */
  51394. SphereParticleEmitter.prototype.getEffectDefines = function () {
  51395. return "#define SPHEREEMITTER";
  51396. };
  51397. /**
  51398. * Returns the string "SphereParticleEmitter"
  51399. * @returns a string containing the class name
  51400. */
  51401. SphereParticleEmitter.prototype.getClassName = function () {
  51402. return "SphereParticleEmitter";
  51403. };
  51404. /**
  51405. * Serializes the particle system to a JSON object.
  51406. * @returns the JSON object
  51407. */
  51408. SphereParticleEmitter.prototype.serialize = function () {
  51409. var serializationObject = {};
  51410. serializationObject.type = this.getClassName();
  51411. serializationObject.radius = this.radius;
  51412. serializationObject.directionRandomizer = this.directionRandomizer;
  51413. return serializationObject;
  51414. };
  51415. /**
  51416. * Parse properties from a JSON object
  51417. * @param serializationObject defines the JSON object
  51418. */
  51419. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  51420. this.radius = serializationObject.radius;
  51421. this.directionRandomizer = serializationObject.directionRandomizer;
  51422. };
  51423. return SphereParticleEmitter;
  51424. }());
  51425. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51426. /**
  51427. * Particle emitter emitting particles from the inside of a sphere.
  51428. * It emits the particles randomly between two vectors.
  51429. */
  51430. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51431. __extends(SphereDirectedParticleEmitter, _super);
  51432. /**
  51433. * Creates a new instance of @see SphereDirectedParticleEmitter
  51434. * @param radius the radius of the emission sphere (1 by default)
  51435. * @param direction1 the min limit of the emission direction (up vector by default)
  51436. * @param direction2 the max limit of the emission direction (up vector by default)
  51437. */
  51438. function SphereDirectedParticleEmitter(radius,
  51439. /**
  51440. * The min limit of the emission direction.
  51441. */
  51442. direction1,
  51443. /**
  51444. * The max limit of the emission direction.
  51445. */
  51446. direction2) {
  51447. if (radius === void 0) { radius = 1; }
  51448. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  51449. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  51450. var _this = _super.call(this, radius) || this;
  51451. _this.direction1 = direction1;
  51452. _this.direction2 = direction2;
  51453. return _this;
  51454. }
  51455. /**
  51456. * Called by the particle System when the direction is computed for the created particle.
  51457. * @param emitPower is the power of the particle (speed)
  51458. * @param worldMatrix is the world matrix of the particle system
  51459. * @param directionToUpdate is the direction vector to update with the result
  51460. * @param particle is the particle we are computed the direction for
  51461. */
  51462. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51463. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51464. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51465. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51466. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51467. };
  51468. /**
  51469. * Clones the current emitter and returns a copy of it
  51470. * @returns the new emitter
  51471. */
  51472. SphereDirectedParticleEmitter.prototype.clone = function () {
  51473. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51474. BABYLON.Tools.DeepCopy(this, newOne);
  51475. return newOne;
  51476. };
  51477. /**
  51478. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51479. * @param effect defines the update shader
  51480. */
  51481. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  51482. effect.setFloat("radius", this.radius);
  51483. effect.setVector3("direction1", this.direction1);
  51484. effect.setVector3("direction2", this.direction2);
  51485. };
  51486. /**
  51487. * Returns a string to use to update the GPU particles update shader
  51488. * @returns a string containng the defines string
  51489. */
  51490. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  51491. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  51492. };
  51493. /**
  51494. * Returns the string "SphereDirectedParticleEmitter"
  51495. * @returns a string containing the class name
  51496. */
  51497. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  51498. return "SphereDirectedParticleEmitter";
  51499. };
  51500. /**
  51501. * Serializes the particle system to a JSON object.
  51502. * @returns the JSON object
  51503. */
  51504. SphereDirectedParticleEmitter.prototype.serialize = function () {
  51505. var serializationObject = _super.prototype.serialize.call(this);
  51506. ;
  51507. serializationObject.direction1 = this.direction1.asArray();
  51508. ;
  51509. serializationObject.direction2 = this.direction2.asArray();
  51510. ;
  51511. return serializationObject;
  51512. };
  51513. /**
  51514. * Parse properties from a JSON object
  51515. * @param serializationObject defines the JSON object
  51516. */
  51517. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  51518. _super.prototype.parse.call(this, serializationObject);
  51519. this.direction1.copyFrom(serializationObject.direction1);
  51520. this.direction2.copyFrom(serializationObject.direction2);
  51521. };
  51522. return SphereDirectedParticleEmitter;
  51523. }(SphereParticleEmitter));
  51524. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51525. })(BABYLON || (BABYLON = {}));
  51526. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51527. var __assign = (this && this.__assign) || Object.assign || function(t) {
  51528. for (var s, i = 1, n = arguments.length; i < n; i++) {
  51529. s = arguments[i];
  51530. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  51531. t[p] = s[p];
  51532. }
  51533. return t;
  51534. };
  51535. var BABYLON;
  51536. (function (BABYLON) {
  51537. /**
  51538. * This represents a GPU particle system in Babylon
  51539. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  51540. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  51541. */
  51542. var GPUParticleSystem = /** @class */ (function () {
  51543. /**
  51544. * Instantiates a GPU particle system.
  51545. * 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.
  51546. * @param name The name of the particle system
  51547. * @param capacity The max number of particles alive at the same time
  51548. * @param scene The scene the particle system belongs to
  51549. */
  51550. function GPUParticleSystem(name, options, scene) {
  51551. /**
  51552. * The emitter represents the Mesh or position we are attaching the particle system to.
  51553. */
  51554. this.emitter = null;
  51555. /**
  51556. * The rendering group used by the Particle system to chose when to render.
  51557. */
  51558. this.renderingGroupId = 0;
  51559. /**
  51560. * The layer mask we are rendering the particles through.
  51561. */
  51562. this.layerMask = 0x0FFFFFFF;
  51563. this._targetIndex = 0;
  51564. this._currentRenderId = -1;
  51565. this._started = false;
  51566. this._stopped = false;
  51567. this._timeDelta = 0;
  51568. this._attributesStrideSize = 14;
  51569. this._actualFrame = 0;
  51570. /**
  51571. * List of animations used by the particle system.
  51572. */
  51573. this.animations = [];
  51574. /**
  51575. * An event triggered when the system is disposed.
  51576. */
  51577. this.onDisposeObservable = new BABYLON.Observable();
  51578. /**
  51579. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51580. */
  51581. this.updateSpeed = 0.01;
  51582. /**
  51583. * The amount of time the particle system is running (depends of the overall update speed).
  51584. */
  51585. this.targetStopDuration = 0;
  51586. /**
  51587. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51588. */
  51589. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  51590. /**
  51591. * Minimum life time of emitting particles.
  51592. */
  51593. this.minLifeTime = 1;
  51594. /**
  51595. * Maximum life time of emitting particles.
  51596. */
  51597. this.maxLifeTime = 1;
  51598. /**
  51599. * Minimum Size of emitting particles.
  51600. */
  51601. this.minSize = 1;
  51602. /**
  51603. * Maximum Size of emitting particles.
  51604. */
  51605. this.maxSize = 1;
  51606. /**
  51607. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51608. */
  51609. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51610. /**
  51611. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51612. */
  51613. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51614. /**
  51615. * Color the particle will have at the end of its lifetime.
  51616. */
  51617. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  51618. /**
  51619. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  51620. */
  51621. this.emitRate = 100;
  51622. /**
  51623. * You can use gravity if you want to give an orientation to your particles.
  51624. */
  51625. this.gravity = BABYLON.Vector3.Zero();
  51626. /**
  51627. * Minimum power of emitting particles.
  51628. */
  51629. this.minEmitPower = 1;
  51630. /**
  51631. * Maximum power of emitting particles.
  51632. */
  51633. this.maxEmitPower = 1;
  51634. this.id = name;
  51635. this.name = name;
  51636. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51637. this._engine = this._scene.getEngine();
  51638. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  51639. this._capacity = fullOptions.capacity;
  51640. this._activeCount = fullOptions.capacity;
  51641. this._currentActiveCount = 0;
  51642. this._scene.particleSystems.push(this);
  51643. this._updateEffectOptions = {
  51644. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  51645. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  51646. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle"],
  51647. uniformBuffersNames: [],
  51648. samplers: ["randomSampler"],
  51649. defines: "",
  51650. fallbacks: null,
  51651. onCompiled: null,
  51652. onError: null,
  51653. indexParameters: null,
  51654. maxSimultaneousLights: 0,
  51655. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  51656. };
  51657. // Random data
  51658. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  51659. var d = [];
  51660. for (var i = 0; i < maxTextureSize; ++i) {
  51661. d.push(Math.random());
  51662. d.push(Math.random());
  51663. d.push(Math.random());
  51664. d.push(Math.random());
  51665. }
  51666. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  51667. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51668. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51669. this._randomTextureSize = maxTextureSize;
  51670. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51671. }
  51672. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  51673. /**
  51674. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  51675. */
  51676. get: function () {
  51677. if (!BABYLON.Engine.LastCreatedEngine) {
  51678. return false;
  51679. }
  51680. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  51681. },
  51682. enumerable: true,
  51683. configurable: true
  51684. });
  51685. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  51686. /**
  51687. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51688. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51689. */
  51690. get: function () {
  51691. if (this.particleEmitterType.direction1) {
  51692. return this.particleEmitterType.direction1;
  51693. }
  51694. return BABYLON.Vector3.Zero();
  51695. },
  51696. set: function (value) {
  51697. if (this.particleEmitterType.direction1) {
  51698. this.particleEmitterType.direction1 = value;
  51699. }
  51700. },
  51701. enumerable: true,
  51702. configurable: true
  51703. });
  51704. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  51705. /**
  51706. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51707. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51708. */
  51709. get: function () {
  51710. if (this.particleEmitterType.direction2) {
  51711. return this.particleEmitterType.direction2;
  51712. }
  51713. return BABYLON.Vector3.Zero();
  51714. },
  51715. set: function (value) {
  51716. if (this.particleEmitterType.direction2) {
  51717. this.particleEmitterType.direction2 = value;
  51718. }
  51719. },
  51720. enumerable: true,
  51721. configurable: true
  51722. });
  51723. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  51724. /**
  51725. * 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.
  51726. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51727. */
  51728. get: function () {
  51729. if (this.particleEmitterType.minEmitBox) {
  51730. return this.particleEmitterType.minEmitBox;
  51731. }
  51732. return BABYLON.Vector3.Zero();
  51733. },
  51734. set: function (value) {
  51735. if (this.particleEmitterType.minEmitBox) {
  51736. this.particleEmitterType.minEmitBox = value;
  51737. }
  51738. },
  51739. enumerable: true,
  51740. configurable: true
  51741. });
  51742. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  51743. /**
  51744. * 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.
  51745. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51746. */
  51747. get: function () {
  51748. if (this.particleEmitterType.maxEmitBox) {
  51749. return this.particleEmitterType.maxEmitBox;
  51750. }
  51751. return BABYLON.Vector3.Zero();
  51752. },
  51753. set: function (value) {
  51754. if (this.particleEmitterType.maxEmitBox) {
  51755. this.particleEmitterType.maxEmitBox = value;
  51756. }
  51757. },
  51758. enumerable: true,
  51759. configurable: true
  51760. });
  51761. /**
  51762. * Gets the maximum number of particles active at the same time.
  51763. * @returns The max number of active particles.
  51764. */
  51765. GPUParticleSystem.prototype.getCapacity = function () {
  51766. return this._capacity;
  51767. };
  51768. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  51769. /**
  51770. * Gets or set the number of active particles
  51771. */
  51772. get: function () {
  51773. return this._activeCount;
  51774. },
  51775. set: function (value) {
  51776. this._activeCount = Math.min(value, this._capacity);
  51777. },
  51778. enumerable: true,
  51779. configurable: true
  51780. });
  51781. /**
  51782. * Gets Wether the system has been started.
  51783. * @returns True if it has been started, otherwise false.
  51784. */
  51785. GPUParticleSystem.prototype.isStarted = function () {
  51786. return this._started;
  51787. };
  51788. /**
  51789. * Starts the particle system and begins to emit.
  51790. */
  51791. GPUParticleSystem.prototype.start = function () {
  51792. this._started = true;
  51793. this._stopped = false;
  51794. };
  51795. /**
  51796. * Stops the particle system.
  51797. */
  51798. GPUParticleSystem.prototype.stop = function () {
  51799. this._stopped = true;
  51800. };
  51801. /**
  51802. * Remove all active particles
  51803. */
  51804. GPUParticleSystem.prototype.reset = function () {
  51805. this._releaseBuffers();
  51806. this._releaseVAOs();
  51807. this._currentActiveCount = 0;
  51808. this._targetIndex = 0;
  51809. };
  51810. /**
  51811. * Returns the string "GPUParticleSystem"
  51812. * @returns a string containing the class name
  51813. */
  51814. GPUParticleSystem.prototype.getClassName = function () {
  51815. return "GPUParticleSystem";
  51816. };
  51817. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  51818. var updateVertexBuffers = {};
  51819. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  51820. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  51821. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  51822. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  51823. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  51824. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  51825. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  51826. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  51827. this._engine.bindArrayBuffer(null);
  51828. return vao;
  51829. };
  51830. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  51831. var renderVertexBuffers = {};
  51832. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  51833. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  51834. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  51835. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  51836. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  51837. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  51838. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  51839. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  51840. this._engine.bindArrayBuffer(null);
  51841. return vao;
  51842. };
  51843. GPUParticleSystem.prototype._initialize = function (force) {
  51844. if (force === void 0) { force = false; }
  51845. if (this._buffer0 && !force) {
  51846. return;
  51847. }
  51848. var engine = this._scene.getEngine();
  51849. var data = new Array();
  51850. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  51851. // position
  51852. data.push(0.0);
  51853. data.push(0.0);
  51854. data.push(0.0);
  51855. // Age and life
  51856. data.push(0.0); // create the particle as a dead one to create a new one at start
  51857. data.push(0.0);
  51858. // Seed
  51859. data.push(Math.random());
  51860. // Size
  51861. data.push(0.0);
  51862. // color
  51863. data.push(0.0);
  51864. data.push(0.0);
  51865. data.push(0.0);
  51866. data.push(0.0);
  51867. // direction
  51868. data.push(0.0);
  51869. data.push(0.0);
  51870. data.push(0.0);
  51871. }
  51872. // Sprite data
  51873. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  51874. -0.5, 0.5, 0, 1,
  51875. -0.5, -0.5, 0, 0,
  51876. 0.5, -0.5, 1, 0]);
  51877. // Buffers
  51878. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  51879. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  51880. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  51881. // Update VAO
  51882. this._updateVAO = [];
  51883. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  51884. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  51885. // Render VAO
  51886. this._renderVAO = [];
  51887. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  51888. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  51889. // Links
  51890. this._sourceBuffer = this._buffer0;
  51891. this._targetBuffer = this._buffer1;
  51892. };
  51893. /** @ignore */
  51894. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  51895. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  51896. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  51897. return;
  51898. }
  51899. this._updateEffectOptions.defines = defines;
  51900. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  51901. };
  51902. /** @ignore */
  51903. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  51904. var defines = "";
  51905. if (this._scene.clipPlane) {
  51906. defines = "\n#define CLIPPLANE";
  51907. }
  51908. if (this._renderEffect && this._renderEffect.defines === defines) {
  51909. return;
  51910. }
  51911. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  51912. };
  51913. /**
  51914. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51915. */
  51916. GPUParticleSystem.prototype.animate = function () {
  51917. if (!this._stopped) {
  51918. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  51919. this._actualFrame += this._timeDelta;
  51920. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51921. this.stop();
  51922. }
  51923. else {
  51924. this._timeDelta = 0;
  51925. }
  51926. };
  51927. /**
  51928. * Renders the particle system in its current state.
  51929. * @returns the current number of particles
  51930. */
  51931. GPUParticleSystem.prototype.render = function () {
  51932. if (!this._started) {
  51933. return 0;
  51934. }
  51935. this._recreateUpdateEffect();
  51936. this._recreateRenderEffect();
  51937. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  51938. return 0;
  51939. }
  51940. if (this._currentRenderId === this._scene.getRenderId()) {
  51941. return 0;
  51942. }
  51943. this._currentRenderId = this._scene.getRenderId();
  51944. // Get everything ready to render
  51945. this._initialize();
  51946. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  51947. // Enable update effect
  51948. this._engine.enableEffect(this._updateEffect);
  51949. this._engine.setState(false);
  51950. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  51951. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  51952. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  51953. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  51954. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  51955. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  51956. this._updateEffect.setDirectColor4("color1", this.color1);
  51957. this._updateEffect.setDirectColor4("color2", this.color2);
  51958. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  51959. this._updateEffect.setVector3("gravity", this.gravity);
  51960. if (this.particleEmitterType) {
  51961. this.particleEmitterType.applyToShader(this._updateEffect);
  51962. }
  51963. var emitterWM;
  51964. if (this.emitter.position) {
  51965. var emitterMesh = this.emitter;
  51966. emitterWM = emitterMesh.getWorldMatrix();
  51967. }
  51968. else {
  51969. var emitterPosition = this.emitter;
  51970. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51971. }
  51972. this._updateEffect.setMatrix("emitterWM", emitterWM);
  51973. // Bind source VAO
  51974. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  51975. // Update
  51976. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  51977. this._engine.setRasterizerState(false);
  51978. this._engine.beginTransformFeedback();
  51979. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  51980. this._engine.endTransformFeedback();
  51981. this._engine.setRasterizerState(true);
  51982. this._engine.bindTransformFeedbackBuffer(null);
  51983. // Enable render effect
  51984. this._engine.enableEffect(this._renderEffect);
  51985. var viewMatrix = this._scene.getViewMatrix();
  51986. this._renderEffect.setMatrix("view", viewMatrix);
  51987. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  51988. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  51989. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  51990. if (this._scene.clipPlane) {
  51991. var clipPlane = this._scene.clipPlane;
  51992. var invView = viewMatrix.clone();
  51993. invView.invert();
  51994. this._renderEffect.setMatrix("invView", invView);
  51995. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51996. }
  51997. // Draw order
  51998. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  51999. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52000. }
  52001. else {
  52002. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52003. }
  52004. // Bind source VAO
  52005. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  52006. // Render
  52007. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  52008. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52009. // Switch VAOs
  52010. this._targetIndex++;
  52011. if (this._targetIndex === 2) {
  52012. this._targetIndex = 0;
  52013. }
  52014. // Switch buffers
  52015. var tmpBuffer = this._sourceBuffer;
  52016. this._sourceBuffer = this._targetBuffer;
  52017. this._targetBuffer = tmpBuffer;
  52018. return this._currentActiveCount;
  52019. };
  52020. /**
  52021. * Rebuilds the particle system
  52022. */
  52023. GPUParticleSystem.prototype.rebuild = function () {
  52024. this._initialize(true);
  52025. };
  52026. GPUParticleSystem.prototype._releaseBuffers = function () {
  52027. if (this._buffer0) {
  52028. this._buffer0.dispose();
  52029. this._buffer0 = null;
  52030. }
  52031. if (this._buffer1) {
  52032. this._buffer1.dispose();
  52033. this._buffer1 = null;
  52034. }
  52035. if (this._spriteBuffer) {
  52036. this._spriteBuffer.dispose();
  52037. this._spriteBuffer = null;
  52038. }
  52039. };
  52040. GPUParticleSystem.prototype._releaseVAOs = function () {
  52041. for (var index = 0; index < this._updateVAO.length; index++) {
  52042. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  52043. }
  52044. this._updateVAO = [];
  52045. for (var index = 0; index < this._renderVAO.length; index++) {
  52046. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  52047. }
  52048. this._renderVAO = [];
  52049. };
  52050. /**
  52051. * Disposes the particle system and free the associated resources.
  52052. */
  52053. GPUParticleSystem.prototype.dispose = function () {
  52054. var index = this._scene.particleSystems.indexOf(this);
  52055. if (index > -1) {
  52056. this._scene.particleSystems.splice(index, 1);
  52057. }
  52058. this._releaseBuffers();
  52059. this._releaseVAOs();
  52060. if (this._randomTexture) {
  52061. this._randomTexture.dispose();
  52062. this._randomTexture = null;
  52063. }
  52064. // Callback
  52065. this.onDisposeObservable.notifyObservers(this);
  52066. this.onDisposeObservable.clear();
  52067. };
  52068. /**
  52069. * Clones the particle system.
  52070. * @param name The name of the cloned object
  52071. * @param newEmitter The new emitter to use
  52072. * @returns the cloned particle system
  52073. */
  52074. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  52075. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  52076. BABYLON.Tools.DeepCopy(this, result);
  52077. if (newEmitter === undefined) {
  52078. newEmitter = this.emitter;
  52079. }
  52080. result.emitter = newEmitter;
  52081. if (this.particleTexture) {
  52082. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52083. }
  52084. return result;
  52085. };
  52086. /**
  52087. * Serializes the particle system to a JSON object.
  52088. * @returns the JSON object
  52089. */
  52090. GPUParticleSystem.prototype.serialize = function () {
  52091. var serializationObject = {};
  52092. serializationObject.name = this.name;
  52093. serializationObject.id = this.id;
  52094. // Emitter
  52095. if (this.emitter.position) {
  52096. var emitterMesh = this.emitter;
  52097. serializationObject.emitterId = emitterMesh.id;
  52098. }
  52099. else {
  52100. var emitterPosition = this.emitter;
  52101. serializationObject.emitter = emitterPosition.asArray();
  52102. }
  52103. serializationObject.capacity = this.getCapacity();
  52104. if (this.particleTexture) {
  52105. serializationObject.textureName = this.particleTexture.name;
  52106. }
  52107. // Animations
  52108. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52109. // Particle system
  52110. serializationObject.activeParticleCount = this.activeParticleCount;
  52111. serializationObject.randomTextureSize = this._randomTextureSize;
  52112. serializationObject.minSize = this.minSize;
  52113. serializationObject.maxSize = this.maxSize;
  52114. serializationObject.minEmitPower = this.minEmitPower;
  52115. serializationObject.maxEmitPower = this.maxEmitPower;
  52116. serializationObject.minLifeTime = this.minLifeTime;
  52117. serializationObject.maxLifeTime = this.maxLifeTime;
  52118. serializationObject.emitRate = this.emitRate;
  52119. serializationObject.gravity = this.gravity.asArray();
  52120. serializationObject.color1 = this.color1.asArray();
  52121. serializationObject.color2 = this.color2.asArray();
  52122. serializationObject.colorDead = this.colorDead.asArray();
  52123. serializationObject.updateSpeed = this.updateSpeed;
  52124. serializationObject.targetStopDuration = this.targetStopDuration;
  52125. serializationObject.blendMode = this.blendMode;
  52126. // Emitter
  52127. if (this.particleEmitterType) {
  52128. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52129. }
  52130. return serializationObject;
  52131. };
  52132. /**
  52133. * Parses a JSON object to create a GPU particle system.
  52134. * @param parsedParticleSystem The JSON object to parse
  52135. * @param scene The scene to create the particle system in
  52136. * @param rootUrl The root url to use to load external dependencies like texture
  52137. * @returns the parsed GPU particle system
  52138. */
  52139. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52140. var name = parsedParticleSystem.name;
  52141. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  52142. if (parsedParticleSystem.id) {
  52143. particleSystem.id = parsedParticleSystem.id;
  52144. }
  52145. // Texture
  52146. if (parsedParticleSystem.textureName) {
  52147. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52148. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52149. }
  52150. // Emitter
  52151. if (parsedParticleSystem.emitterId) {
  52152. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52153. }
  52154. else {
  52155. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52156. }
  52157. // Animations
  52158. if (parsedParticleSystem.animations) {
  52159. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52160. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52161. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52162. }
  52163. }
  52164. // Particle system
  52165. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  52166. particleSystem.minSize = parsedParticleSystem.minSize;
  52167. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52168. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52169. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52170. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52171. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52172. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52173. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52174. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52175. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52176. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52177. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52178. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52179. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52180. // Emitter
  52181. if (parsedParticleSystem.particleEmitterType) {
  52182. var emitterType = void 0;
  52183. switch (parsedParticleSystem.particleEmitterType.type) {
  52184. case "SphereEmitter":
  52185. emitterType = new BABYLON.SphereParticleEmitter();
  52186. break;
  52187. case "SphereDirectedParticleEmitter":
  52188. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  52189. break;
  52190. case "ConeEmitter":
  52191. emitterType = new BABYLON.ConeParticleEmitter();
  52192. break;
  52193. case "BoxEmitter":
  52194. default:
  52195. emitterType = new BABYLON.BoxParticleEmitter();
  52196. break;
  52197. }
  52198. emitterType.parse(parsedParticleSystem.particleEmitterType);
  52199. particleSystem.particleEmitterType = emitterType;
  52200. }
  52201. return particleSystem;
  52202. };
  52203. return GPUParticleSystem;
  52204. }());
  52205. BABYLON.GPUParticleSystem = GPUParticleSystem;
  52206. })(BABYLON || (BABYLON = {}));
  52207. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  52208. var BABYLON;
  52209. (function (BABYLON) {
  52210. /**
  52211. * Represents one particle of a solid particle system.
  52212. * @see SolidParticleSystem
  52213. */
  52214. var SolidParticle = /** @class */ (function () {
  52215. /**
  52216. * Creates a Solid Particle object.
  52217. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52218. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52219. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52220. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52221. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52222. * @param shapeId (integer) is the model shape identifier in the SPS.
  52223. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52224. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52225. */
  52226. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52227. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52228. /**
  52229. * particle global index
  52230. */
  52231. this.idx = 0;
  52232. /**
  52233. * The color of the particle
  52234. */
  52235. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52236. /**
  52237. * The world space position of the particle.
  52238. */
  52239. this.position = BABYLON.Vector3.Zero();
  52240. /**
  52241. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52242. */
  52243. this.rotation = BABYLON.Vector3.Zero();
  52244. /**
  52245. * The scaling of the particle.
  52246. */
  52247. this.scaling = BABYLON.Vector3.One();
  52248. /**
  52249. * The uvs of the particle.
  52250. */
  52251. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52252. /**
  52253. * The current speed of the particle.
  52254. */
  52255. this.velocity = BABYLON.Vector3.Zero();
  52256. /**
  52257. * The pivot point in the particle local space.
  52258. */
  52259. this.pivot = BABYLON.Vector3.Zero();
  52260. /**
  52261. * Must the particle be translated from its pivot point in its local space ?
  52262. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52263. * Default : false
  52264. */
  52265. this.translateFromPivot = false;
  52266. /**
  52267. * Is the particle active or not ?
  52268. */
  52269. this.alive = true;
  52270. /**
  52271. * Is the particle visible or not ?
  52272. */
  52273. this.isVisible = true;
  52274. /**
  52275. * Index of this particle in the global "positions" array (Internal use)
  52276. */
  52277. this._pos = 0;
  52278. /**
  52279. * Index of this particle in the global "indices" array (Internal use)
  52280. */
  52281. this._ind = 0;
  52282. /**
  52283. * ModelShape id of this particle
  52284. */
  52285. this.shapeId = 0;
  52286. /**
  52287. * Index of the particle in its shape id (Internal use)
  52288. */
  52289. this.idxInShape = 0;
  52290. /**
  52291. * Still set as invisible in order to skip useless computations (Internal use)
  52292. */
  52293. this._stillInvisible = false;
  52294. /**
  52295. * Last computed particle rotation matrix
  52296. */
  52297. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52298. /**
  52299. * Parent particle Id, if any.
  52300. * Default null.
  52301. */
  52302. this.parentId = null;
  52303. /**
  52304. * Internal global position in the SPS.
  52305. */
  52306. this._globalPosition = BABYLON.Vector3.Zero();
  52307. this.idx = particleIndex;
  52308. this._pos = positionIndex;
  52309. this._ind = indiceIndex;
  52310. this._model = model;
  52311. this.shapeId = shapeId;
  52312. this.idxInShape = idxInShape;
  52313. this._sps = sps;
  52314. if (modelBoundingInfo) {
  52315. this._modelBoundingInfo = modelBoundingInfo;
  52316. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52317. }
  52318. }
  52319. Object.defineProperty(SolidParticle.prototype, "scale", {
  52320. /**
  52321. * Legacy support, changed scale to scaling
  52322. */
  52323. get: function () {
  52324. return this.scaling;
  52325. },
  52326. /**
  52327. * Legacy support, changed scale to scaling
  52328. */
  52329. set: function (scale) {
  52330. this.scaling = scale;
  52331. },
  52332. enumerable: true,
  52333. configurable: true
  52334. });
  52335. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52336. /**
  52337. * Legacy support, changed quaternion to rotationQuaternion
  52338. */
  52339. get: function () {
  52340. return this.rotationQuaternion;
  52341. },
  52342. /**
  52343. * Legacy support, changed quaternion to rotationQuaternion
  52344. */
  52345. set: function (q) {
  52346. this.rotationQuaternion = q;
  52347. },
  52348. enumerable: true,
  52349. configurable: true
  52350. });
  52351. /**
  52352. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52353. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52354. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52355. * @returns true if it intersects
  52356. */
  52357. SolidParticle.prototype.intersectsMesh = function (target) {
  52358. if (!this._boundingInfo || !target._boundingInfo) {
  52359. return false;
  52360. }
  52361. if (this._sps._bSphereOnly) {
  52362. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52363. }
  52364. return this._boundingInfo.intersects(target._boundingInfo, false);
  52365. };
  52366. return SolidParticle;
  52367. }());
  52368. BABYLON.SolidParticle = SolidParticle;
  52369. /**
  52370. * Represents the shape of the model used by one particle of a solid particle system.
  52371. * SPS internal tool, don't use it manually.
  52372. * @see SolidParticleSystem
  52373. */
  52374. var ModelShape = /** @class */ (function () {
  52375. /**
  52376. * 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.
  52377. * SPS internal tool, don't use it manually.
  52378. * @ignore
  52379. */
  52380. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52381. /**
  52382. * length of the shape in the model indices array (internal use)
  52383. */
  52384. this._indicesLength = 0;
  52385. this.shapeID = id;
  52386. this._shape = shape;
  52387. this._indicesLength = indicesLength;
  52388. this._shapeUV = shapeUV;
  52389. this._positionFunction = posFunction;
  52390. this._vertexFunction = vtxFunction;
  52391. }
  52392. return ModelShape;
  52393. }());
  52394. BABYLON.ModelShape = ModelShape;
  52395. /**
  52396. * Represents a Depth Sorted Particle in the solid particle system.
  52397. * @see SolidParticleSystem
  52398. */
  52399. var DepthSortedParticle = /** @class */ (function () {
  52400. function DepthSortedParticle() {
  52401. /**
  52402. * Index of the particle in the "indices" array
  52403. */
  52404. this.ind = 0;
  52405. /**
  52406. * Length of the particle shape in the "indices" array
  52407. */
  52408. this.indicesLength = 0;
  52409. /**
  52410. * Squared distance from the particle to the camera
  52411. */
  52412. this.sqDistance = 0.0;
  52413. }
  52414. return DepthSortedParticle;
  52415. }());
  52416. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52417. })(BABYLON || (BABYLON = {}));
  52418. //# sourceMappingURL=babylon.solidParticle.js.map
  52419. var BABYLON;
  52420. (function (BABYLON) {
  52421. /**
  52422. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  52423. *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.
  52424. * The SPS is also a particle system. It provides some methods to manage the particles.
  52425. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  52426. *
  52427. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52428. */
  52429. var SolidParticleSystem = /** @class */ (function () {
  52430. /**
  52431. * Creates a SPS (Solid Particle System) object.
  52432. * @param name (String) is the SPS name, this will be the underlying mesh name.
  52433. * @param scene (Scene) is the scene in which the SPS is added.
  52434. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  52435. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  52436. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  52437. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  52438. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52439. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52440. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52441. */
  52442. function SolidParticleSystem(name, scene, options) {
  52443. /**
  52444. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52445. * Example : var p = SPS.particles[i];
  52446. */
  52447. this.particles = new Array();
  52448. /**
  52449. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52450. */
  52451. this.nbParticles = 0;
  52452. /**
  52453. * If the particles must ever face the camera (default false). Useful for planar particles.
  52454. */
  52455. this.billboard = false;
  52456. /**
  52457. * Recompute normals when adding a shape
  52458. */
  52459. this.recomputeNormals = true;
  52460. /**
  52461. * This a counter ofr your own usage. It's not set by any SPS functions.
  52462. */
  52463. this.counter = 0;
  52464. /**
  52465. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52466. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52467. */
  52468. this.vars = {};
  52469. /**
  52470. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52471. */
  52472. this._bSphereOnly = false;
  52473. /**
  52474. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52475. */
  52476. this._bSphereRadiusFactor = 1.0;
  52477. this._positions = new Array();
  52478. this._indices = new Array();
  52479. this._normals = new Array();
  52480. this._colors = new Array();
  52481. this._uvs = new Array();
  52482. this._index = 0; // indices index
  52483. this._updatable = true;
  52484. this._pickable = false;
  52485. this._isVisibilityBoxLocked = false;
  52486. this._alwaysVisible = false;
  52487. this._depthSort = false;
  52488. this._shapeCounter = 0;
  52489. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52490. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52491. this._computeParticleColor = true;
  52492. this._computeParticleTexture = true;
  52493. this._computeParticleRotation = true;
  52494. this._computeParticleVertex = false;
  52495. this._computeBoundingBox = false;
  52496. this._depthSortParticles = true;
  52497. this._cam_axisZ = BABYLON.Vector3.Zero();
  52498. this._cam_axisY = BABYLON.Vector3.Zero();
  52499. this._cam_axisX = BABYLON.Vector3.Zero();
  52500. this._axisZ = BABYLON.Axis.Z;
  52501. this._camDir = BABYLON.Vector3.Zero();
  52502. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52503. this._rotMatrix = new BABYLON.Matrix();
  52504. this._invertMatrix = new BABYLON.Matrix();
  52505. this._rotated = BABYLON.Vector3.Zero();
  52506. this._quaternion = new BABYLON.Quaternion();
  52507. this._vertex = BABYLON.Vector3.Zero();
  52508. this._normal = BABYLON.Vector3.Zero();
  52509. this._yaw = 0.0;
  52510. this._pitch = 0.0;
  52511. this._roll = 0.0;
  52512. this._halfroll = 0.0;
  52513. this._halfpitch = 0.0;
  52514. this._halfyaw = 0.0;
  52515. this._sinRoll = 0.0;
  52516. this._cosRoll = 0.0;
  52517. this._sinPitch = 0.0;
  52518. this._cosPitch = 0.0;
  52519. this._sinYaw = 0.0;
  52520. this._cosYaw = 0.0;
  52521. this._mustUnrotateFixedNormals = false;
  52522. this._minimum = BABYLON.Vector3.Zero();
  52523. this._maximum = BABYLON.Vector3.Zero();
  52524. this._minBbox = BABYLON.Vector3.Zero();
  52525. this._maxBbox = BABYLON.Vector3.Zero();
  52526. this._particlesIntersect = false;
  52527. this._depthSortFunction = function (p1, p2) {
  52528. return (p2.sqDistance - p1.sqDistance);
  52529. };
  52530. this._needs32Bits = false;
  52531. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52532. this._scaledPivot = BABYLON.Vector3.Zero();
  52533. this._particleHasParent = false;
  52534. this.name = name;
  52535. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52536. this._camera = scene.activeCamera;
  52537. this._pickable = options ? options.isPickable : false;
  52538. this._depthSort = options ? options.enableDepthSort : false;
  52539. this._particlesIntersect = options ? options.particleIntersection : false;
  52540. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52541. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52542. if (options && options.updatable) {
  52543. this._updatable = options.updatable;
  52544. }
  52545. else {
  52546. this._updatable = true;
  52547. }
  52548. if (this._pickable) {
  52549. this.pickedParticles = [];
  52550. }
  52551. if (this._depthSort) {
  52552. this.depthSortedParticles = [];
  52553. }
  52554. }
  52555. /**
  52556. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52557. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52558. * @returns the created mesh
  52559. */
  52560. SolidParticleSystem.prototype.buildMesh = function () {
  52561. if (this.nbParticles === 0) {
  52562. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52563. this.addShape(triangle, 1);
  52564. triangle.dispose();
  52565. }
  52566. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52567. this._positions32 = new Float32Array(this._positions);
  52568. this._uvs32 = new Float32Array(this._uvs);
  52569. this._colors32 = new Float32Array(this._colors);
  52570. if (this.recomputeNormals) {
  52571. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52572. }
  52573. this._normals32 = new Float32Array(this._normals);
  52574. this._fixedNormal32 = new Float32Array(this._normals);
  52575. if (this._mustUnrotateFixedNormals) {
  52576. this._unrotateFixedNormals();
  52577. }
  52578. var vertexData = new BABYLON.VertexData();
  52579. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52580. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52581. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52582. if (this._uvs32) {
  52583. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52584. ;
  52585. }
  52586. if (this._colors32) {
  52587. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52588. }
  52589. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52590. vertexData.applyToMesh(mesh, this._updatable);
  52591. this.mesh = mesh;
  52592. this.mesh.isPickable = this._pickable;
  52593. // free memory
  52594. if (!this._depthSort) {
  52595. this._indices = null;
  52596. }
  52597. this._positions = null;
  52598. this._normals = null;
  52599. this._uvs = null;
  52600. this._colors = null;
  52601. if (!this._updatable) {
  52602. this.particles.length = 0;
  52603. }
  52604. return mesh;
  52605. };
  52606. /**
  52607. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52608. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52609. * Thus the particles generated from `digest()` have their property `position` set yet.
  52610. * @param mesh ( Mesh ) is the mesh to be digested
  52611. * @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
  52612. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52613. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52614. * @returns the current SPS
  52615. */
  52616. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52617. var size = (options && options.facetNb) || 1;
  52618. var number = (options && options.number) || 0;
  52619. var delta = (options && options.delta) || 0;
  52620. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52621. var meshInd = mesh.getIndices();
  52622. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52623. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52624. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52625. var f = 0; // facet counter
  52626. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52627. // compute size from number
  52628. if (number) {
  52629. number = (number > totalFacets) ? totalFacets : number;
  52630. size = Math.round(totalFacets / number);
  52631. delta = 0;
  52632. }
  52633. else {
  52634. size = (size > totalFacets) ? totalFacets : size;
  52635. }
  52636. var facetPos = []; // submesh positions
  52637. var facetInd = []; // submesh indices
  52638. var facetUV = []; // submesh UV
  52639. var facetCol = []; // submesh colors
  52640. var barycenter = BABYLON.Vector3.Zero();
  52641. var sizeO = size;
  52642. while (f < totalFacets) {
  52643. size = sizeO + Math.floor((1 + delta) * Math.random());
  52644. if (f > totalFacets - size) {
  52645. size = totalFacets - f;
  52646. }
  52647. // reset temp arrays
  52648. facetPos.length = 0;
  52649. facetInd.length = 0;
  52650. facetUV.length = 0;
  52651. facetCol.length = 0;
  52652. // iterate over "size" facets
  52653. var fi = 0;
  52654. for (var j = f * 3; j < (f + size) * 3; j++) {
  52655. facetInd.push(fi);
  52656. var i = meshInd[j];
  52657. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52658. if (meshUV) {
  52659. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52660. }
  52661. if (meshCol) {
  52662. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52663. }
  52664. fi++;
  52665. }
  52666. // create a model shape for each single particle
  52667. var idx = this.nbParticles;
  52668. var shape = this._posToShape(facetPos);
  52669. var shapeUV = this._uvsToShapeUV(facetUV);
  52670. // compute the barycenter of the shape
  52671. var v;
  52672. for (v = 0; v < shape.length; v++) {
  52673. barycenter.addInPlace(shape[v]);
  52674. }
  52675. barycenter.scaleInPlace(1 / shape.length);
  52676. // shift the shape from its barycenter to the origin
  52677. for (v = 0; v < shape.length; v++) {
  52678. shape[v].subtractInPlace(barycenter);
  52679. }
  52680. var bInfo;
  52681. if (this._particlesIntersect) {
  52682. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52683. }
  52684. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  52685. // add the particle in the SPS
  52686. var currentPos = this._positions.length;
  52687. var currentInd = this._indices.length;
  52688. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52689. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  52690. // initialize the particle position
  52691. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52692. this._index += shape.length;
  52693. idx++;
  52694. this.nbParticles++;
  52695. this._shapeCounter++;
  52696. f += size;
  52697. }
  52698. return this;
  52699. };
  52700. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52701. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52702. var index = 0;
  52703. var idx = 0;
  52704. for (var p = 0; p < this.particles.length; p++) {
  52705. this._particle = this.particles[p];
  52706. this._shape = this._particle._model._shape;
  52707. if (this._particle.rotationQuaternion) {
  52708. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52709. }
  52710. else {
  52711. this._yaw = this._particle.rotation.y;
  52712. this._pitch = this._particle.rotation.x;
  52713. this._roll = this._particle.rotation.z;
  52714. this._quaternionRotationYPR();
  52715. }
  52716. this._quaternionToRotationMatrix();
  52717. this._rotMatrix.invertToRef(this._invertMatrix);
  52718. for (var pt = 0; pt < this._shape.length; pt++) {
  52719. idx = index + pt * 3;
  52720. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52721. this._fixedNormal32[idx] = this._normal.x;
  52722. this._fixedNormal32[idx + 1] = this._normal.y;
  52723. this._fixedNormal32[idx + 2] = this._normal.z;
  52724. }
  52725. index = idx + 3;
  52726. }
  52727. };
  52728. //reset copy
  52729. SolidParticleSystem.prototype._resetCopy = function () {
  52730. this._copy.position.x = 0;
  52731. this._copy.position.y = 0;
  52732. this._copy.position.z = 0;
  52733. this._copy.rotation.x = 0;
  52734. this._copy.rotation.y = 0;
  52735. this._copy.rotation.z = 0;
  52736. this._copy.rotationQuaternion = null;
  52737. this._copy.scaling.x = 1.0;
  52738. this._copy.scaling.y = 1.0;
  52739. this._copy.scaling.z = 1.0;
  52740. this._copy.uvs.x = 0;
  52741. this._copy.uvs.y = 0;
  52742. this._copy.uvs.z = 1.0;
  52743. this._copy.uvs.w = 1.0;
  52744. this._copy.color = null;
  52745. this._copy.translateFromPivot = false;
  52746. };
  52747. // _meshBuilder : inserts the shape model in the global SPS mesh
  52748. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52749. var i;
  52750. var u = 0;
  52751. var c = 0;
  52752. var n = 0;
  52753. this._resetCopy();
  52754. if (options && options.positionFunction) {
  52755. options.positionFunction(this._copy, idx, idxInShape);
  52756. this._mustUnrotateFixedNormals = true;
  52757. }
  52758. if (this._copy.rotationQuaternion) {
  52759. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52760. }
  52761. else {
  52762. this._yaw = this._copy.rotation.y;
  52763. this._pitch = this._copy.rotation.x;
  52764. this._roll = this._copy.rotation.z;
  52765. this._quaternionRotationYPR();
  52766. }
  52767. this._quaternionToRotationMatrix();
  52768. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  52769. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  52770. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  52771. if (this._copy.translateFromPivot) {
  52772. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52773. }
  52774. else {
  52775. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52776. }
  52777. for (i = 0; i < shape.length; i++) {
  52778. this._vertex.x = shape[i].x;
  52779. this._vertex.y = shape[i].y;
  52780. this._vertex.z = shape[i].z;
  52781. if (options && options.vertexFunction) {
  52782. options.vertexFunction(this._copy, this._vertex, i);
  52783. }
  52784. this._vertex.x *= this._copy.scaling.x;
  52785. this._vertex.y *= this._copy.scaling.y;
  52786. this._vertex.z *= this._copy.scaling.z;
  52787. this._vertex.x -= this._scaledPivot.x;
  52788. this._vertex.y -= this._scaledPivot.y;
  52789. this._vertex.z -= this._scaledPivot.z;
  52790. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52791. this._rotated.addInPlace(this._pivotBackTranslation);
  52792. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52793. if (meshUV) {
  52794. 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);
  52795. u += 2;
  52796. }
  52797. if (this._copy.color) {
  52798. this._color = this._copy.color;
  52799. }
  52800. else if (meshCol && meshCol[c] !== undefined) {
  52801. this._color.r = meshCol[c];
  52802. this._color.g = meshCol[c + 1];
  52803. this._color.b = meshCol[c + 2];
  52804. this._color.a = meshCol[c + 3];
  52805. }
  52806. else {
  52807. this._color.r = 1.0;
  52808. this._color.g = 1.0;
  52809. this._color.b = 1.0;
  52810. this._color.a = 1.0;
  52811. }
  52812. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52813. c += 4;
  52814. if (!this.recomputeNormals && meshNor) {
  52815. this._normal.x = meshNor[n];
  52816. this._normal.y = meshNor[n + 1];
  52817. this._normal.z = meshNor[n + 2];
  52818. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52819. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52820. n += 3;
  52821. }
  52822. }
  52823. for (i = 0; i < meshInd.length; i++) {
  52824. var current_ind = p + meshInd[i];
  52825. indices.push(current_ind);
  52826. if (current_ind > 65535) {
  52827. this._needs32Bits = true;
  52828. }
  52829. }
  52830. if (this._pickable) {
  52831. var nbfaces = meshInd.length / 3;
  52832. for (i = 0; i < nbfaces; i++) {
  52833. this.pickedParticles.push({ idx: idx, faceId: i });
  52834. }
  52835. }
  52836. if (this._depthSort) {
  52837. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  52838. }
  52839. return this._copy;
  52840. };
  52841. // returns a shape array from positions array
  52842. SolidParticleSystem.prototype._posToShape = function (positions) {
  52843. var shape = [];
  52844. for (var i = 0; i < positions.length; i += 3) {
  52845. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52846. }
  52847. return shape;
  52848. };
  52849. // returns a shapeUV array from a Vector4 uvs
  52850. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52851. var shapeUV = [];
  52852. if (uvs) {
  52853. for (var i = 0; i < uvs.length; i++)
  52854. shapeUV.push(uvs[i]);
  52855. }
  52856. return shapeUV;
  52857. };
  52858. // adds a new particle object in the particles array
  52859. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  52860. if (bInfo === void 0) { bInfo = null; }
  52861. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  52862. this.particles.push(sp);
  52863. return sp;
  52864. };
  52865. /**
  52866. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52867. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52868. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  52869. * @param nb (positive integer) the number of particles to be created from this model
  52870. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  52871. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  52872. * @returns the number of shapes in the system
  52873. */
  52874. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52875. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52876. var meshInd = mesh.getIndices();
  52877. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52878. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52879. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52880. var bbInfo;
  52881. if (this._particlesIntersect) {
  52882. bbInfo = mesh.getBoundingInfo();
  52883. }
  52884. var shape = this._posToShape(meshPos);
  52885. var shapeUV = this._uvsToShapeUV(meshUV);
  52886. var posfunc = options ? options.positionFunction : null;
  52887. var vtxfunc = options ? options.vertexFunction : null;
  52888. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  52889. // particles
  52890. var sp;
  52891. var currentCopy;
  52892. var idx = this.nbParticles;
  52893. for (var i = 0; i < nb; i++) {
  52894. var currentPos = this._positions.length;
  52895. var currentInd = this._indices.length;
  52896. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52897. if (this._updatable) {
  52898. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  52899. sp.position.copyFrom(currentCopy.position);
  52900. sp.rotation.copyFrom(currentCopy.rotation);
  52901. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  52902. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52903. }
  52904. if (currentCopy.color && sp.color) {
  52905. sp.color.copyFrom(currentCopy.color);
  52906. }
  52907. sp.scaling.copyFrom(currentCopy.scaling);
  52908. sp.uvs.copyFrom(currentCopy.uvs);
  52909. }
  52910. this._index += shape.length;
  52911. idx++;
  52912. }
  52913. this.nbParticles += nb;
  52914. this._shapeCounter++;
  52915. return this._shapeCounter - 1;
  52916. };
  52917. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52918. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52919. this._resetCopy();
  52920. if (particle._model._positionFunction) {
  52921. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52922. }
  52923. if (this._copy.rotationQuaternion) {
  52924. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52925. }
  52926. else {
  52927. this._yaw = this._copy.rotation.y;
  52928. this._pitch = this._copy.rotation.x;
  52929. this._roll = this._copy.rotation.z;
  52930. this._quaternionRotationYPR();
  52931. }
  52932. this._quaternionToRotationMatrix();
  52933. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52934. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52935. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52936. if (this._copy.translateFromPivot) {
  52937. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52938. }
  52939. else {
  52940. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52941. }
  52942. this._shape = particle._model._shape;
  52943. for (var pt = 0; pt < this._shape.length; pt++) {
  52944. this._vertex.x = this._shape[pt].x;
  52945. this._vertex.y = this._shape[pt].y;
  52946. this._vertex.z = this._shape[pt].z;
  52947. if (particle._model._vertexFunction) {
  52948. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52949. }
  52950. this._vertex.x *= this._copy.scaling.x;
  52951. this._vertex.y *= this._copy.scaling.y;
  52952. this._vertex.z *= this._copy.scaling.z;
  52953. this._vertex.x -= this._scaledPivot.x;
  52954. this._vertex.y -= this._scaledPivot.y;
  52955. this._vertex.z -= this._scaledPivot.z;
  52956. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52957. this._rotated.addInPlace(this._pivotBackTranslation);
  52958. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52959. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52960. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52961. }
  52962. particle.position.x = 0.0;
  52963. particle.position.y = 0.0;
  52964. particle.position.z = 0.0;
  52965. particle.rotation.x = 0.0;
  52966. particle.rotation.y = 0.0;
  52967. particle.rotation.z = 0.0;
  52968. particle.rotationQuaternion = null;
  52969. particle.scaling.x = 1.0;
  52970. particle.scaling.y = 1.0;
  52971. particle.scaling.z = 1.0;
  52972. particle.uvs.x = 0.0;
  52973. particle.uvs.y = 0.0;
  52974. particle.uvs.z = 1.0;
  52975. particle.uvs.w = 1.0;
  52976. particle.pivot.x = 0.0;
  52977. particle.pivot.y = 0.0;
  52978. particle.pivot.z = 0.0;
  52979. particle.translateFromPivot = false;
  52980. particle.parentId = null;
  52981. };
  52982. /**
  52983. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52984. * @returns the SPS.
  52985. */
  52986. SolidParticleSystem.prototype.rebuildMesh = function () {
  52987. for (var p = 0; p < this.particles.length; p++) {
  52988. this._rebuildParticle(this.particles[p]);
  52989. }
  52990. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52991. return this;
  52992. };
  52993. /**
  52994. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52995. * This method calls `updateParticle()` for each particle of the SPS.
  52996. * For an animated SPS, it is usually called within the render loop.
  52997. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52998. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52999. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53000. * @returns the SPS.
  53001. */
  53002. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53003. if (start === void 0) { start = 0; }
  53004. if (end === void 0) { end = this.nbParticles - 1; }
  53005. if (update === void 0) { update = true; }
  53006. if (!this._updatable) {
  53007. return this;
  53008. }
  53009. // custom beforeUpdate
  53010. this.beforeUpdateParticles(start, end, update);
  53011. this._cam_axisX.x = 1.0;
  53012. this._cam_axisX.y = 0.0;
  53013. this._cam_axisX.z = 0.0;
  53014. this._cam_axisY.x = 0.0;
  53015. this._cam_axisY.y = 1.0;
  53016. this._cam_axisY.z = 0.0;
  53017. this._cam_axisZ.x = 0.0;
  53018. this._cam_axisZ.y = 0.0;
  53019. this._cam_axisZ.z = 1.0;
  53020. // cases when the World Matrix is to be computed first
  53021. if (this.billboard || this._depthSort) {
  53022. this.mesh.computeWorldMatrix(true);
  53023. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53024. }
  53025. // if the particles will always face the camera
  53026. if (this.billboard) {
  53027. // compute the camera position and un-rotate it by the current mesh rotation
  53028. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53029. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53030. this._cam_axisZ.normalize();
  53031. // same for camera up vector extracted from the cam view matrix
  53032. var view = this._camera.getViewMatrix(true);
  53033. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53034. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53035. this._cam_axisY.normalize();
  53036. this._cam_axisX.normalize();
  53037. }
  53038. // if depthSort, compute the camera global position in the mesh local system
  53039. if (this._depthSort) {
  53040. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53041. }
  53042. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53043. var idx = 0; // current position index in the global array positions32
  53044. var index = 0; // position start index in the global array positions32 of the current particle
  53045. var colidx = 0; // current color index in the global array colors32
  53046. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53047. var uvidx = 0; // current uv index in the global array uvs32
  53048. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53049. var pt = 0; // current index in the particle model shape
  53050. if (this.mesh.isFacetDataEnabled) {
  53051. this._computeBoundingBox = true;
  53052. }
  53053. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53054. if (this._computeBoundingBox) {
  53055. if (start == 0 && end == this.nbParticles - 1) {
  53056. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53057. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53058. }
  53059. else {
  53060. if (this.mesh._boundingInfo) {
  53061. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53062. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53063. }
  53064. }
  53065. }
  53066. // particle loop
  53067. index = this.particles[start]._pos;
  53068. var vpos = (index / 3) | 0;
  53069. colorIndex = vpos * 4;
  53070. uvIndex = vpos * 2;
  53071. for (var p = start; p <= end; p++) {
  53072. this._particle = this.particles[p];
  53073. this._shape = this._particle._model._shape;
  53074. this._shapeUV = this._particle._model._shapeUV;
  53075. // call to custom user function to update the particle properties
  53076. this.updateParticle(this._particle);
  53077. // camera-particle distance for depth sorting
  53078. if (this._depthSort && this._depthSortParticles) {
  53079. var dsp = this.depthSortedParticles[p];
  53080. dsp.ind = this._particle._ind;
  53081. dsp.indicesLength = this._particle._model._indicesLength;
  53082. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53083. }
  53084. // skip the computations for inactive or already invisible particles
  53085. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53086. // increment indexes for the next particle
  53087. pt = this._shape.length;
  53088. index += pt * 3;
  53089. colorIndex += pt * 4;
  53090. uvIndex += pt * 2;
  53091. continue;
  53092. }
  53093. if (this._particle.isVisible) {
  53094. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53095. this._particleHasParent = (this._particle.parentId !== null);
  53096. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53097. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53098. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53099. // particle rotation matrix
  53100. if (this.billboard) {
  53101. this._particle.rotation.x = 0.0;
  53102. this._particle.rotation.y = 0.0;
  53103. }
  53104. if (this._computeParticleRotation || this.billboard) {
  53105. if (this._particle.rotationQuaternion) {
  53106. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53107. }
  53108. else {
  53109. this._yaw = this._particle.rotation.y;
  53110. this._pitch = this._particle.rotation.x;
  53111. this._roll = this._particle.rotation.z;
  53112. this._quaternionRotationYPR();
  53113. }
  53114. this._quaternionToRotationMatrix();
  53115. }
  53116. if (this._particleHasParent) {
  53117. this._parent = this.particles[this._particle.parentId];
  53118. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  53119. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  53120. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  53121. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53122. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53123. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53124. if (this._computeParticleRotation || this.billboard) {
  53125. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  53126. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  53127. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  53128. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  53129. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  53130. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  53131. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  53132. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  53133. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  53134. }
  53135. }
  53136. else {
  53137. this._particle._globalPosition.x = this._particle.position.x;
  53138. this._particle._globalPosition.y = this._particle.position.y;
  53139. this._particle._globalPosition.z = this._particle.position.z;
  53140. if (this._computeParticleRotation || this.billboard) {
  53141. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53142. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53143. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53144. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53145. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53146. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53147. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53148. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53149. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53150. }
  53151. }
  53152. if (this._particle.translateFromPivot) {
  53153. this._pivotBackTranslation.x = 0.0;
  53154. this._pivotBackTranslation.y = 0.0;
  53155. this._pivotBackTranslation.z = 0.0;
  53156. }
  53157. else {
  53158. this._pivotBackTranslation.x = this._scaledPivot.x;
  53159. this._pivotBackTranslation.y = this._scaledPivot.y;
  53160. this._pivotBackTranslation.z = this._scaledPivot.z;
  53161. }
  53162. // particle vertex loop
  53163. for (pt = 0; pt < this._shape.length; pt++) {
  53164. idx = index + pt * 3;
  53165. colidx = colorIndex + pt * 4;
  53166. uvidx = uvIndex + pt * 2;
  53167. this._vertex.x = this._shape[pt].x;
  53168. this._vertex.y = this._shape[pt].y;
  53169. this._vertex.z = this._shape[pt].z;
  53170. if (this._computeParticleVertex) {
  53171. this.updateParticleVertex(this._particle, this._vertex, pt);
  53172. }
  53173. // positions
  53174. this._vertex.x *= this._particle.scaling.x;
  53175. this._vertex.y *= this._particle.scaling.y;
  53176. this._vertex.z *= this._particle.scaling.z;
  53177. this._vertex.x -= this._scaledPivot.x;
  53178. this._vertex.y -= this._scaledPivot.y;
  53179. this._vertex.z -= this._scaledPivot.z;
  53180. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53181. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53182. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53183. this._rotated.x += this._pivotBackTranslation.x;
  53184. this._rotated.y += this._pivotBackTranslation.y;
  53185. this._rotated.z += this._pivotBackTranslation.z;
  53186. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53187. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  53188. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  53189. if (this._computeBoundingBox) {
  53190. if (this._positions32[idx] < this._minimum.x) {
  53191. this._minimum.x = this._positions32[idx];
  53192. }
  53193. if (this._positions32[idx] > this._maximum.x) {
  53194. this._maximum.x = this._positions32[idx];
  53195. }
  53196. if (this._positions32[idx + 1] < this._minimum.y) {
  53197. this._minimum.y = this._positions32[idx + 1];
  53198. }
  53199. if (this._positions32[idx + 1] > this._maximum.y) {
  53200. this._maximum.y = this._positions32[idx + 1];
  53201. }
  53202. if (this._positions32[idx + 2] < this._minimum.z) {
  53203. this._minimum.z = this._positions32[idx + 2];
  53204. }
  53205. if (this._positions32[idx + 2] > this._maximum.z) {
  53206. this._maximum.z = this._positions32[idx + 2];
  53207. }
  53208. }
  53209. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53210. if (!this._computeParticleVertex) {
  53211. this._normal.x = this._fixedNormal32[idx];
  53212. this._normal.y = this._fixedNormal32[idx + 1];
  53213. this._normal.z = this._fixedNormal32[idx + 2];
  53214. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53215. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53216. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53217. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53218. 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;
  53219. 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;
  53220. }
  53221. if (this._computeParticleColor && this._particle.color) {
  53222. this._colors32[colidx] = this._particle.color.r;
  53223. this._colors32[colidx + 1] = this._particle.color.g;
  53224. this._colors32[colidx + 2] = this._particle.color.b;
  53225. this._colors32[colidx + 3] = this._particle.color.a;
  53226. }
  53227. if (this._computeParticleTexture) {
  53228. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53229. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53230. }
  53231. }
  53232. }
  53233. else {
  53234. this._particle._stillInvisible = true; // mark the particle as invisible
  53235. for (pt = 0; pt < this._shape.length; pt++) {
  53236. idx = index + pt * 3;
  53237. colidx = colorIndex + pt * 4;
  53238. uvidx = uvIndex + pt * 2;
  53239. this._positions32[idx] = 0.0;
  53240. this._positions32[idx + 1] = 0.0;
  53241. this._positions32[idx + 2] = 0.0;
  53242. this._normals32[idx] = 0.0;
  53243. this._normals32[idx + 1] = 0.0;
  53244. this._normals32[idx + 2] = 0.0;
  53245. if (this._computeParticleColor && this._particle.color) {
  53246. this._colors32[colidx] = this._particle.color.r;
  53247. this._colors32[colidx + 1] = this._particle.color.g;
  53248. this._colors32[colidx + 2] = this._particle.color.b;
  53249. this._colors32[colidx + 3] = this._particle.color.a;
  53250. }
  53251. if (this._computeParticleTexture) {
  53252. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53253. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53254. }
  53255. }
  53256. }
  53257. // if the particle intersections must be computed : update the bbInfo
  53258. if (this._particlesIntersect) {
  53259. var bInfo = this._particle._boundingInfo;
  53260. var bBox = bInfo.boundingBox;
  53261. var bSphere = bInfo.boundingSphere;
  53262. if (!this._bSphereOnly) {
  53263. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53264. for (var b = 0; b < bBox.vectors.length; b++) {
  53265. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53266. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53267. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53268. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53269. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53270. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53271. 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;
  53272. 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;
  53273. 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;
  53274. }
  53275. bBox._update(this.mesh._worldMatrix);
  53276. }
  53277. // place and scale the particle bouding sphere in the SPS local system, then update it
  53278. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53279. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53280. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53281. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53282. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53283. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53284. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53285. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53286. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53287. 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));
  53288. bSphere._update(this.mesh._worldMatrix);
  53289. }
  53290. // increment indexes for the next particle
  53291. index = idx + 3;
  53292. colorIndex = colidx + 4;
  53293. uvIndex = uvidx + 2;
  53294. }
  53295. // if the VBO must be updated
  53296. if (update) {
  53297. if (this._computeParticleColor) {
  53298. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53299. }
  53300. if (this._computeParticleTexture) {
  53301. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53302. }
  53303. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53304. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53305. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53306. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53307. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53308. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53309. for (var i = 0; i < this._normals32.length; i++) {
  53310. this._fixedNormal32[i] = this._normals32[i];
  53311. }
  53312. }
  53313. if (!this.mesh.areNormalsFrozen) {
  53314. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53315. }
  53316. }
  53317. if (this._depthSort && this._depthSortParticles) {
  53318. this.depthSortedParticles.sort(this._depthSortFunction);
  53319. var dspl = this.depthSortedParticles.length;
  53320. var sorted = 0;
  53321. var lind = 0;
  53322. var sind = 0;
  53323. var sid = 0;
  53324. for (sorted = 0; sorted < dspl; sorted++) {
  53325. lind = this.depthSortedParticles[sorted].indicesLength;
  53326. sind = this.depthSortedParticles[sorted].ind;
  53327. for (var i = 0; i < lind; i++) {
  53328. this._indices32[sid] = this._indices[sind + i];
  53329. sid++;
  53330. }
  53331. }
  53332. this.mesh.updateIndices(this._indices32);
  53333. }
  53334. }
  53335. if (this._computeBoundingBox) {
  53336. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53337. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53338. }
  53339. this.afterUpdateParticles(start, end, update);
  53340. return this;
  53341. };
  53342. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53343. this._halfroll = this._roll * 0.5;
  53344. this._halfpitch = this._pitch * 0.5;
  53345. this._halfyaw = this._yaw * 0.5;
  53346. this._sinRoll = Math.sin(this._halfroll);
  53347. this._cosRoll = Math.cos(this._halfroll);
  53348. this._sinPitch = Math.sin(this._halfpitch);
  53349. this._cosPitch = Math.cos(this._halfpitch);
  53350. this._sinYaw = Math.sin(this._halfyaw);
  53351. this._cosYaw = Math.cos(this._halfyaw);
  53352. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53353. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53354. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53355. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53356. };
  53357. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53358. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53359. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53360. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53361. this._rotMatrix.m[3] = 0;
  53362. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53363. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53364. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53365. this._rotMatrix.m[7] = 0;
  53366. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53367. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53368. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53369. this._rotMatrix.m[11] = 0;
  53370. this._rotMatrix.m[12] = 0;
  53371. this._rotMatrix.m[13] = 0;
  53372. this._rotMatrix.m[14] = 0;
  53373. this._rotMatrix.m[15] = 1.0;
  53374. };
  53375. /**
  53376. * Disposes the SPS.
  53377. */
  53378. SolidParticleSystem.prototype.dispose = function () {
  53379. this.mesh.dispose();
  53380. this.vars = null;
  53381. // drop references to internal big arrays for the GC
  53382. this._positions = null;
  53383. this._indices = null;
  53384. this._normals = null;
  53385. this._uvs = null;
  53386. this._colors = null;
  53387. this._indices32 = null;
  53388. this._positions32 = null;
  53389. this._normals32 = null;
  53390. this._fixedNormal32 = null;
  53391. this._uvs32 = null;
  53392. this._colors32 = null;
  53393. this.pickedParticles = null;
  53394. };
  53395. /**
  53396. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53397. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53398. * @returns the SPS.
  53399. */
  53400. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53401. if (!this._isVisibilityBoxLocked) {
  53402. this.mesh.refreshBoundingInfo();
  53403. }
  53404. return this;
  53405. };
  53406. /**
  53407. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53408. * @param size the size (float) of the visibility box
  53409. * note : this doesn't lock the SPS mesh bounding box.
  53410. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53411. */
  53412. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53413. var vis = size / 2;
  53414. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53415. };
  53416. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53417. /**
  53418. * Gets whether the SPS as always visible or not
  53419. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53420. */
  53421. get: function () {
  53422. return this._alwaysVisible;
  53423. },
  53424. /**
  53425. * Sets the SPS as always visible or not
  53426. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53427. */
  53428. set: function (val) {
  53429. this._alwaysVisible = val;
  53430. this.mesh.alwaysSelectAsActiveMesh = val;
  53431. },
  53432. enumerable: true,
  53433. configurable: true
  53434. });
  53435. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53436. /**
  53437. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53438. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53439. */
  53440. get: function () {
  53441. return this._isVisibilityBoxLocked;
  53442. },
  53443. /**
  53444. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53445. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53446. */
  53447. set: function (val) {
  53448. this._isVisibilityBoxLocked = val;
  53449. var boundingInfo = this.mesh.getBoundingInfo();
  53450. boundingInfo.isLocked = val;
  53451. },
  53452. enumerable: true,
  53453. configurable: true
  53454. });
  53455. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53456. /**
  53457. * Gets if `setParticles()` computes the particle rotations or not.
  53458. * Default value : true. The SPS is faster when it's set to false.
  53459. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53460. */
  53461. get: function () {
  53462. return this._computeParticleRotation;
  53463. },
  53464. /**
  53465. * Tells to `setParticles()` to compute the particle rotations or not.
  53466. * Default value : true. The SPS is faster when it's set to false.
  53467. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53468. */
  53469. set: function (val) {
  53470. this._computeParticleRotation = val;
  53471. },
  53472. enumerable: true,
  53473. configurable: true
  53474. });
  53475. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53476. /**
  53477. * Gets if `setParticles()` computes the particle colors or not.
  53478. * Default value : true. The SPS is faster when it's set to false.
  53479. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53480. */
  53481. get: function () {
  53482. return this._computeParticleColor;
  53483. },
  53484. /**
  53485. * Tells to `setParticles()` to compute the particle colors or not.
  53486. * Default value : true. The SPS is faster when it's set to false.
  53487. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53488. */
  53489. set: function (val) {
  53490. this._computeParticleColor = val;
  53491. },
  53492. enumerable: true,
  53493. configurable: true
  53494. });
  53495. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53496. /**
  53497. * Gets if `setParticles()` computes the particle textures or not.
  53498. * Default value : true. The SPS is faster when it's set to false.
  53499. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53500. */
  53501. get: function () {
  53502. return this._computeParticleTexture;
  53503. },
  53504. set: function (val) {
  53505. this._computeParticleTexture = val;
  53506. },
  53507. enumerable: true,
  53508. configurable: true
  53509. });
  53510. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53511. /**
  53512. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53513. * Default value : false. The SPS is faster when it's set to false.
  53514. * Note : the particle custom vertex positions aren't stored values.
  53515. */
  53516. get: function () {
  53517. return this._computeParticleVertex;
  53518. },
  53519. /**
  53520. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53521. * Default value : false. The SPS is faster when it's set to false.
  53522. * Note : the particle custom vertex positions aren't stored values.
  53523. */
  53524. set: function (val) {
  53525. this._computeParticleVertex = val;
  53526. },
  53527. enumerable: true,
  53528. configurable: true
  53529. });
  53530. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53531. /**
  53532. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53533. */
  53534. get: function () {
  53535. return this._computeBoundingBox;
  53536. },
  53537. /**
  53538. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53539. */
  53540. set: function (val) {
  53541. this._computeBoundingBox = val;
  53542. },
  53543. enumerable: true,
  53544. configurable: true
  53545. });
  53546. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53547. /**
  53548. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53549. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53550. * Default : `true`
  53551. */
  53552. get: function () {
  53553. return this._depthSortParticles;
  53554. },
  53555. /**
  53556. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53557. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53558. * Default : `true`
  53559. */
  53560. set: function (val) {
  53561. this._depthSortParticles = val;
  53562. },
  53563. enumerable: true,
  53564. configurable: true
  53565. });
  53566. // =======================================================================
  53567. // Particle behavior logic
  53568. // these following methods may be overwritten by the user to fit his needs
  53569. /**
  53570. * This function does nothing. It may be overwritten to set all the particle first values.
  53571. * The SPS doesn't call this function, you may have to call it by your own.
  53572. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53573. */
  53574. SolidParticleSystem.prototype.initParticles = function () {
  53575. };
  53576. /**
  53577. * This function does nothing. It may be overwritten to recycle a particle.
  53578. * The SPS doesn't call this function, you may have to call it by your own.
  53579. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53580. * @param particle The particle to recycle
  53581. * @returns the recycled particle
  53582. */
  53583. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53584. return particle;
  53585. };
  53586. /**
  53587. * Updates a particle : this function should be overwritten by the user.
  53588. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53589. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53590. * @example : just set a particle position or velocity and recycle conditions
  53591. * @param particle The particle to update
  53592. * @returns the updated particle
  53593. */
  53594. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53595. return particle;
  53596. };
  53597. /**
  53598. * Updates a vertex of a particle : it can be overwritten by the user.
  53599. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53600. * @param particle the current particle
  53601. * @param vertex the current index of the current particle
  53602. * @param pt the index of the current vertex in the particle shape
  53603. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53604. * @example : just set a vertex particle position
  53605. * @returns the updated vertex
  53606. */
  53607. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53608. return vertex;
  53609. };
  53610. /**
  53611. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53612. * This does nothing and may be overwritten by the user.
  53613. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53614. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53615. * @param update the boolean update value actually passed to setParticles()
  53616. */
  53617. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53618. };
  53619. /**
  53620. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53621. * This will be passed three parameters.
  53622. * This does nothing and may be overwritten by the user.
  53623. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53624. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53625. * @param update the boolean update value actually passed to setParticles()
  53626. */
  53627. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53628. };
  53629. return SolidParticleSystem;
  53630. }());
  53631. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53632. })(BABYLON || (BABYLON = {}));
  53633. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53634. var BABYLON;
  53635. (function (BABYLON) {
  53636. var ShaderMaterial = /** @class */ (function (_super) {
  53637. __extends(ShaderMaterial, _super);
  53638. function ShaderMaterial(name, scene, shaderPath, options) {
  53639. var _this = _super.call(this, name, scene) || this;
  53640. _this._textures = {};
  53641. _this._textureArrays = {};
  53642. _this._floats = {};
  53643. _this._ints = {};
  53644. _this._floatsArrays = {};
  53645. _this._colors3 = {};
  53646. _this._colors3Arrays = {};
  53647. _this._colors4 = {};
  53648. _this._vectors2 = {};
  53649. _this._vectors3 = {};
  53650. _this._vectors4 = {};
  53651. _this._matrices = {};
  53652. _this._matrices3x3 = {};
  53653. _this._matrices2x2 = {};
  53654. _this._vectors2Arrays = {};
  53655. _this._vectors3Arrays = {};
  53656. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  53657. _this._shaderPath = shaderPath;
  53658. options.needAlphaBlending = options.needAlphaBlending || false;
  53659. options.needAlphaTesting = options.needAlphaTesting || false;
  53660. options.attributes = options.attributes || ["position", "normal", "uv"];
  53661. options.uniforms = options.uniforms || ["worldViewProjection"];
  53662. options.uniformBuffers = options.uniformBuffers || [];
  53663. options.samplers = options.samplers || [];
  53664. options.defines = options.defines || [];
  53665. _this._options = options;
  53666. return _this;
  53667. }
  53668. ShaderMaterial.prototype.getClassName = function () {
  53669. return "ShaderMaterial";
  53670. };
  53671. ShaderMaterial.prototype.needAlphaBlending = function () {
  53672. return this._options.needAlphaBlending;
  53673. };
  53674. ShaderMaterial.prototype.needAlphaTesting = function () {
  53675. return this._options.needAlphaTesting;
  53676. };
  53677. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  53678. if (this._options.uniforms.indexOf(uniformName) === -1) {
  53679. this._options.uniforms.push(uniformName);
  53680. }
  53681. };
  53682. ShaderMaterial.prototype.setTexture = function (name, texture) {
  53683. if (this._options.samplers.indexOf(name) === -1) {
  53684. this._options.samplers.push(name);
  53685. }
  53686. this._textures[name] = texture;
  53687. return this;
  53688. };
  53689. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  53690. if (this._options.samplers.indexOf(name) === -1) {
  53691. this._options.samplers.push(name);
  53692. }
  53693. this._checkUniform(name);
  53694. this._textureArrays[name] = textures;
  53695. return this;
  53696. };
  53697. ShaderMaterial.prototype.setFloat = function (name, value) {
  53698. this._checkUniform(name);
  53699. this._floats[name] = value;
  53700. return this;
  53701. };
  53702. ShaderMaterial.prototype.setInt = function (name, value) {
  53703. this._checkUniform(name);
  53704. this._ints[name] = value;
  53705. return this;
  53706. };
  53707. ShaderMaterial.prototype.setFloats = function (name, value) {
  53708. this._checkUniform(name);
  53709. this._floatsArrays[name] = value;
  53710. return this;
  53711. };
  53712. ShaderMaterial.prototype.setColor3 = function (name, value) {
  53713. this._checkUniform(name);
  53714. this._colors3[name] = value;
  53715. return this;
  53716. };
  53717. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  53718. this._checkUniform(name);
  53719. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  53720. color.toArray(arr, arr.length);
  53721. return arr;
  53722. }, []);
  53723. return this;
  53724. };
  53725. ShaderMaterial.prototype.setColor4 = function (name, value) {
  53726. this._checkUniform(name);
  53727. this._colors4[name] = value;
  53728. return this;
  53729. };
  53730. ShaderMaterial.prototype.setVector2 = function (name, value) {
  53731. this._checkUniform(name);
  53732. this._vectors2[name] = value;
  53733. return this;
  53734. };
  53735. ShaderMaterial.prototype.setVector3 = function (name, value) {
  53736. this._checkUniform(name);
  53737. this._vectors3[name] = value;
  53738. return this;
  53739. };
  53740. ShaderMaterial.prototype.setVector4 = function (name, value) {
  53741. this._checkUniform(name);
  53742. this._vectors4[name] = value;
  53743. return this;
  53744. };
  53745. ShaderMaterial.prototype.setMatrix = function (name, value) {
  53746. this._checkUniform(name);
  53747. this._matrices[name] = value;
  53748. return this;
  53749. };
  53750. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  53751. this._checkUniform(name);
  53752. this._matrices3x3[name] = value;
  53753. return this;
  53754. };
  53755. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  53756. this._checkUniform(name);
  53757. this._matrices2x2[name] = value;
  53758. return this;
  53759. };
  53760. ShaderMaterial.prototype.setArray2 = function (name, value) {
  53761. this._checkUniform(name);
  53762. this._vectors2Arrays[name] = value;
  53763. return this;
  53764. };
  53765. ShaderMaterial.prototype.setArray3 = function (name, value) {
  53766. this._checkUniform(name);
  53767. this._vectors3Arrays[name] = value;
  53768. return this;
  53769. };
  53770. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53771. if (!mesh) {
  53772. return true;
  53773. }
  53774. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  53775. return false;
  53776. }
  53777. return false;
  53778. };
  53779. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  53780. var scene = this.getScene();
  53781. var engine = scene.getEngine();
  53782. if (!this.checkReadyOnEveryCall) {
  53783. if (this._renderId === scene.getRenderId()) {
  53784. if (this._checkCache(scene, mesh, useInstances)) {
  53785. return true;
  53786. }
  53787. }
  53788. }
  53789. // Instances
  53790. var defines = [];
  53791. var attribs = [];
  53792. var fallbacks = new BABYLON.EffectFallbacks();
  53793. if (useInstances) {
  53794. defines.push("#define INSTANCES");
  53795. }
  53796. for (var index = 0; index < this._options.defines.length; index++) {
  53797. defines.push(this._options.defines[index]);
  53798. }
  53799. for (var index = 0; index < this._options.attributes.length; index++) {
  53800. attribs.push(this._options.attributes[index]);
  53801. }
  53802. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53803. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53804. defines.push("#define VERTEXCOLOR");
  53805. }
  53806. // Bones
  53807. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  53808. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53809. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53810. if (mesh.numBoneInfluencers > 4) {
  53811. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53812. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53813. }
  53814. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53815. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53816. fallbacks.addCPUSkinningFallback(0, mesh);
  53817. if (this._options.uniforms.indexOf("mBones") === -1) {
  53818. this._options.uniforms.push("mBones");
  53819. }
  53820. }
  53821. else {
  53822. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53823. }
  53824. // Textures
  53825. for (var name in this._textures) {
  53826. if (!this._textures[name].isReady()) {
  53827. return false;
  53828. }
  53829. }
  53830. // Alpha test
  53831. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  53832. defines.push("#define ALPHATEST");
  53833. }
  53834. var previousEffect = this._effect;
  53835. var join = defines.join("\n");
  53836. this._effect = engine.createEffect(this._shaderPath, {
  53837. attributes: attribs,
  53838. uniformsNames: this._options.uniforms,
  53839. uniformBuffersNames: this._options.uniformBuffers,
  53840. samplers: this._options.samplers,
  53841. defines: join,
  53842. fallbacks: fallbacks,
  53843. onCompiled: this.onCompiled,
  53844. onError: this.onError
  53845. }, engine);
  53846. if (!this._effect.isReady()) {
  53847. return false;
  53848. }
  53849. if (previousEffect !== this._effect) {
  53850. scene.resetCachedMaterial();
  53851. }
  53852. this._renderId = scene.getRenderId();
  53853. return true;
  53854. };
  53855. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53856. var scene = this.getScene();
  53857. if (!this._effect) {
  53858. return;
  53859. }
  53860. if (this._options.uniforms.indexOf("world") !== -1) {
  53861. this._effect.setMatrix("world", world);
  53862. }
  53863. if (this._options.uniforms.indexOf("worldView") !== -1) {
  53864. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  53865. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  53866. }
  53867. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  53868. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  53869. }
  53870. };
  53871. ShaderMaterial.prototype.bind = function (world, mesh) {
  53872. // Std values
  53873. this.bindOnlyWorldMatrix(world);
  53874. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  53875. if (this._options.uniforms.indexOf("view") !== -1) {
  53876. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  53877. }
  53878. if (this._options.uniforms.indexOf("projection") !== -1) {
  53879. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  53880. }
  53881. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  53882. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  53883. }
  53884. // Bones
  53885. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53886. var name;
  53887. // Texture
  53888. for (name in this._textures) {
  53889. this._effect.setTexture(name, this._textures[name]);
  53890. }
  53891. // Texture arrays
  53892. for (name in this._textureArrays) {
  53893. this._effect.setTextureArray(name, this._textureArrays[name]);
  53894. }
  53895. // Int
  53896. for (name in this._ints) {
  53897. this._effect.setInt(name, this._ints[name]);
  53898. }
  53899. // Float
  53900. for (name in this._floats) {
  53901. this._effect.setFloat(name, this._floats[name]);
  53902. }
  53903. // Floats
  53904. for (name in this._floatsArrays) {
  53905. this._effect.setArray(name, this._floatsArrays[name]);
  53906. }
  53907. // Color3
  53908. for (name in this._colors3) {
  53909. this._effect.setColor3(name, this._colors3[name]);
  53910. }
  53911. for (name in this._colors3Arrays) {
  53912. this._effect.setArray3(name, this._colors3Arrays[name]);
  53913. }
  53914. // Color4
  53915. for (name in this._colors4) {
  53916. var color = this._colors4[name];
  53917. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53918. }
  53919. // Vector2
  53920. for (name in this._vectors2) {
  53921. this._effect.setVector2(name, this._vectors2[name]);
  53922. }
  53923. // Vector3
  53924. for (name in this._vectors3) {
  53925. this._effect.setVector3(name, this._vectors3[name]);
  53926. }
  53927. // Vector4
  53928. for (name in this._vectors4) {
  53929. this._effect.setVector4(name, this._vectors4[name]);
  53930. }
  53931. // Matrix
  53932. for (name in this._matrices) {
  53933. this._effect.setMatrix(name, this._matrices[name]);
  53934. }
  53935. // Matrix 3x3
  53936. for (name in this._matrices3x3) {
  53937. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53938. }
  53939. // Matrix 2x2
  53940. for (name in this._matrices2x2) {
  53941. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53942. }
  53943. // Vector2Array
  53944. for (name in this._vectors2Arrays) {
  53945. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53946. }
  53947. // Vector3Array
  53948. for (name in this._vectors3Arrays) {
  53949. this._effect.setArray3(name, this._vectors3Arrays[name]);
  53950. }
  53951. }
  53952. this._afterBind(mesh);
  53953. };
  53954. ShaderMaterial.prototype.getActiveTextures = function () {
  53955. var activeTextures = _super.prototype.getActiveTextures.call(this);
  53956. for (var name in this._textures) {
  53957. activeTextures.push(this._textures[name]);
  53958. }
  53959. for (var name in this._textureArrays) {
  53960. var array = this._textureArrays[name];
  53961. for (var index = 0; index < array.length; index++) {
  53962. activeTextures.push(array[index]);
  53963. }
  53964. }
  53965. return activeTextures;
  53966. };
  53967. ShaderMaterial.prototype.hasTexture = function (texture) {
  53968. if (_super.prototype.hasTexture.call(this, texture)) {
  53969. return true;
  53970. }
  53971. for (var name in this._textures) {
  53972. if (this._textures[name] === texture) {
  53973. return true;
  53974. }
  53975. }
  53976. for (var name in this._textureArrays) {
  53977. var array = this._textureArrays[name];
  53978. for (var index = 0; index < array.length; index++) {
  53979. if (array[index] === texture) {
  53980. return true;
  53981. }
  53982. }
  53983. }
  53984. return false;
  53985. };
  53986. ShaderMaterial.prototype.clone = function (name) {
  53987. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  53988. return newShaderMaterial;
  53989. };
  53990. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53991. if (forceDisposeTextures) {
  53992. var name;
  53993. for (name in this._textures) {
  53994. this._textures[name].dispose();
  53995. }
  53996. for (name in this._textureArrays) {
  53997. var array = this._textureArrays[name];
  53998. for (var index = 0; index < array.length; index++) {
  53999. array[index].dispose();
  54000. }
  54001. }
  54002. }
  54003. this._textures = {};
  54004. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54005. };
  54006. ShaderMaterial.prototype.serialize = function () {
  54007. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54008. serializationObject.customType = "BABYLON.ShaderMaterial";
  54009. serializationObject.options = this._options;
  54010. serializationObject.shaderPath = this._shaderPath;
  54011. var name;
  54012. // Texture
  54013. serializationObject.textures = {};
  54014. for (name in this._textures) {
  54015. serializationObject.textures[name] = this._textures[name].serialize();
  54016. }
  54017. // Texture arrays
  54018. serializationObject.textureArrays = {};
  54019. for (name in this._textureArrays) {
  54020. serializationObject.textureArrays[name] = [];
  54021. var array = this._textureArrays[name];
  54022. for (var index = 0; index < array.length; index++) {
  54023. serializationObject.textureArrays[name].push(array[index].serialize());
  54024. }
  54025. }
  54026. // Float
  54027. serializationObject.floats = {};
  54028. for (name in this._floats) {
  54029. serializationObject.floats[name] = this._floats[name];
  54030. }
  54031. // Float s
  54032. serializationObject.FloatArrays = {};
  54033. for (name in this._floatsArrays) {
  54034. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54035. }
  54036. // Color3
  54037. serializationObject.colors3 = {};
  54038. for (name in this._colors3) {
  54039. serializationObject.colors3[name] = this._colors3[name].asArray();
  54040. }
  54041. // Color3 array
  54042. serializationObject.colors3Arrays = {};
  54043. for (name in this._colors3Arrays) {
  54044. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54045. }
  54046. // Color4
  54047. serializationObject.colors4 = {};
  54048. for (name in this._colors4) {
  54049. serializationObject.colors4[name] = this._colors4[name].asArray();
  54050. }
  54051. // Vector2
  54052. serializationObject.vectors2 = {};
  54053. for (name in this._vectors2) {
  54054. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54055. }
  54056. // Vector3
  54057. serializationObject.vectors3 = {};
  54058. for (name in this._vectors3) {
  54059. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54060. }
  54061. // Vector4
  54062. serializationObject.vectors4 = {};
  54063. for (name in this._vectors4) {
  54064. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54065. }
  54066. // Matrix
  54067. serializationObject.matrices = {};
  54068. for (name in this._matrices) {
  54069. serializationObject.matrices[name] = this._matrices[name].asArray();
  54070. }
  54071. // Matrix 3x3
  54072. serializationObject.matrices3x3 = {};
  54073. for (name in this._matrices3x3) {
  54074. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54075. }
  54076. // Matrix 2x2
  54077. serializationObject.matrices2x2 = {};
  54078. for (name in this._matrices2x2) {
  54079. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54080. }
  54081. // Vector2Array
  54082. serializationObject.vectors2Arrays = {};
  54083. for (name in this._vectors2Arrays) {
  54084. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54085. }
  54086. // Vector3Array
  54087. serializationObject.vectors3Arrays = {};
  54088. for (name in this._vectors3Arrays) {
  54089. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54090. }
  54091. return serializationObject;
  54092. };
  54093. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54094. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54095. var name;
  54096. // Texture
  54097. for (name in source.textures) {
  54098. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54099. }
  54100. // Texture arrays
  54101. for (name in source.textureArrays) {
  54102. var array = source.textureArrays[name];
  54103. var textureArray = new Array();
  54104. for (var index = 0; index < array.length; index++) {
  54105. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54106. }
  54107. material.setTextureArray(name, textureArray);
  54108. }
  54109. // Float
  54110. for (name in source.floats) {
  54111. material.setFloat(name, source.floats[name]);
  54112. }
  54113. // Float s
  54114. for (name in source.floatsArrays) {
  54115. material.setFloats(name, source.floatsArrays[name]);
  54116. }
  54117. // Color3
  54118. for (name in source.colors3) {
  54119. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54120. }
  54121. // Color3 arrays
  54122. for (name in source.colors3Arrays) {
  54123. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54124. if (i % 3 === 0) {
  54125. arr.push([num]);
  54126. }
  54127. else {
  54128. arr[arr.length - 1].push(num);
  54129. }
  54130. return arr;
  54131. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54132. material.setColor3Array(name, colors);
  54133. }
  54134. // Color4
  54135. for (name in source.colors4) {
  54136. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54137. }
  54138. // Vector2
  54139. for (name in source.vectors2) {
  54140. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54141. }
  54142. // Vector3
  54143. for (name in source.vectors3) {
  54144. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54145. }
  54146. // Vector4
  54147. for (name in source.vectors4) {
  54148. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54149. }
  54150. // Matrix
  54151. for (name in source.matrices) {
  54152. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54153. }
  54154. // Matrix 3x3
  54155. for (name in source.matrices3x3) {
  54156. material.setMatrix3x3(name, source.matrices3x3[name]);
  54157. }
  54158. // Matrix 2x2
  54159. for (name in source.matrices2x2) {
  54160. material.setMatrix2x2(name, source.matrices2x2[name]);
  54161. }
  54162. // Vector2Array
  54163. for (name in source.vectors2Arrays) {
  54164. material.setArray2(name, source.vectors2Arrays[name]);
  54165. }
  54166. // Vector3Array
  54167. for (name in source.vectors3Arrays) {
  54168. material.setArray3(name, source.vectors3Arrays[name]);
  54169. }
  54170. return material;
  54171. };
  54172. return ShaderMaterial;
  54173. }(BABYLON.Material));
  54174. BABYLON.ShaderMaterial = ShaderMaterial;
  54175. })(BABYLON || (BABYLON = {}));
  54176. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54177. var BABYLON;
  54178. (function (BABYLON) {
  54179. var GroundMesh = /** @class */ (function (_super) {
  54180. __extends(GroundMesh, _super);
  54181. function GroundMesh(name, scene) {
  54182. var _this = _super.call(this, name, scene) || this;
  54183. _this.generateOctree = false;
  54184. return _this;
  54185. }
  54186. GroundMesh.prototype.getClassName = function () {
  54187. return "GroundMesh";
  54188. };
  54189. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54190. get: function () {
  54191. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54192. },
  54193. enumerable: true,
  54194. configurable: true
  54195. });
  54196. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54197. get: function () {
  54198. return this._subdivisionsX;
  54199. },
  54200. enumerable: true,
  54201. configurable: true
  54202. });
  54203. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54204. get: function () {
  54205. return this._subdivisionsY;
  54206. },
  54207. enumerable: true,
  54208. configurable: true
  54209. });
  54210. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54211. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54212. this._subdivisionsX = chunksCount;
  54213. this._subdivisionsY = chunksCount;
  54214. this.subdivide(chunksCount);
  54215. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54216. };
  54217. /**
  54218. * Returns a height (y) value in the Worl system :
  54219. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54220. * Returns the ground y position if (x, z) are outside the ground surface.
  54221. */
  54222. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54223. var world = this.getWorldMatrix();
  54224. var invMat = BABYLON.Tmp.Matrix[5];
  54225. world.invertToRef(invMat);
  54226. var tmpVect = BABYLON.Tmp.Vector3[8];
  54227. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54228. x = tmpVect.x;
  54229. z = tmpVect.z;
  54230. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54231. return this.position.y;
  54232. }
  54233. if (!this._heightQuads || this._heightQuads.length == 0) {
  54234. this._initHeightQuads();
  54235. this._computeHeightQuads();
  54236. }
  54237. var facet = this._getFacetAt(x, z);
  54238. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54239. // return y in the World system
  54240. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54241. return tmpVect.y;
  54242. };
  54243. /**
  54244. * Returns a normalized vector (Vector3) orthogonal to the ground
  54245. * at the ground coordinates (x, z) expressed in the World system.
  54246. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54247. */
  54248. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54249. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54250. this.getNormalAtCoordinatesToRef(x, z, normal);
  54251. return normal;
  54252. };
  54253. /**
  54254. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54255. * at the ground coordinates (x, z) expressed in the World system.
  54256. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54257. * Returns the GroundMesh.
  54258. */
  54259. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54260. var world = this.getWorldMatrix();
  54261. var tmpMat = BABYLON.Tmp.Matrix[5];
  54262. world.invertToRef(tmpMat);
  54263. var tmpVect = BABYLON.Tmp.Vector3[8];
  54264. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54265. x = tmpVect.x;
  54266. z = tmpVect.z;
  54267. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54268. return this;
  54269. }
  54270. if (!this._heightQuads || this._heightQuads.length == 0) {
  54271. this._initHeightQuads();
  54272. this._computeHeightQuads();
  54273. }
  54274. var facet = this._getFacetAt(x, z);
  54275. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54276. return this;
  54277. };
  54278. /**
  54279. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54280. * if the ground has been updated.
  54281. * This can be used in the render loop.
  54282. * Returns the GroundMesh.
  54283. */
  54284. GroundMesh.prototype.updateCoordinateHeights = function () {
  54285. if (!this._heightQuads || this._heightQuads.length == 0) {
  54286. this._initHeightQuads();
  54287. }
  54288. this._computeHeightQuads();
  54289. return this;
  54290. };
  54291. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54292. GroundMesh.prototype._getFacetAt = function (x, z) {
  54293. // retrieve col and row from x, z coordinates in the ground local system
  54294. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54295. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54296. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54297. var facet;
  54298. if (z < quad.slope.x * x + quad.slope.y) {
  54299. facet = quad.facet1;
  54300. }
  54301. else {
  54302. facet = quad.facet2;
  54303. }
  54304. return facet;
  54305. };
  54306. // Creates and populates the heightMap array with "facet" elements :
  54307. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54308. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54309. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54310. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54311. // Returns the GroundMesh.
  54312. GroundMesh.prototype._initHeightQuads = function () {
  54313. var subdivisionsX = this._subdivisionsX;
  54314. var subdivisionsY = this._subdivisionsY;
  54315. this._heightQuads = new Array();
  54316. for (var row = 0; row < subdivisionsY; row++) {
  54317. for (var col = 0; col < subdivisionsX; col++) {
  54318. 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) };
  54319. this._heightQuads[row * subdivisionsX + col] = quad;
  54320. }
  54321. }
  54322. return this;
  54323. };
  54324. // Compute each quad element values and update the the heightMap array :
  54325. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54326. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54327. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54328. // Returns the GroundMesh.
  54329. GroundMesh.prototype._computeHeightQuads = function () {
  54330. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54331. if (!positions) {
  54332. return this;
  54333. }
  54334. var v1 = BABYLON.Tmp.Vector3[3];
  54335. var v2 = BABYLON.Tmp.Vector3[2];
  54336. var v3 = BABYLON.Tmp.Vector3[1];
  54337. var v4 = BABYLON.Tmp.Vector3[0];
  54338. var v1v2 = BABYLON.Tmp.Vector3[4];
  54339. var v1v3 = BABYLON.Tmp.Vector3[5];
  54340. var v1v4 = BABYLON.Tmp.Vector3[6];
  54341. var norm1 = BABYLON.Tmp.Vector3[7];
  54342. var norm2 = BABYLON.Tmp.Vector3[8];
  54343. var i = 0;
  54344. var j = 0;
  54345. var k = 0;
  54346. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54347. var h = 0;
  54348. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54349. var d2 = 0;
  54350. var subdivisionsX = this._subdivisionsX;
  54351. var subdivisionsY = this._subdivisionsY;
  54352. for (var row = 0; row < subdivisionsY; row++) {
  54353. for (var col = 0; col < subdivisionsX; col++) {
  54354. i = col * 3;
  54355. j = row * (subdivisionsX + 1) * 3;
  54356. k = (row + 1) * (subdivisionsX + 1) * 3;
  54357. v1.x = positions[j + i];
  54358. v1.y = positions[j + i + 1];
  54359. v1.z = positions[j + i + 2];
  54360. v2.x = positions[j + i + 3];
  54361. v2.y = positions[j + i + 4];
  54362. v2.z = positions[j + i + 5];
  54363. v3.x = positions[k + i];
  54364. v3.y = positions[k + i + 1];
  54365. v3.z = positions[k + i + 2];
  54366. v4.x = positions[k + i + 3];
  54367. v4.y = positions[k + i + 4];
  54368. v4.z = positions[k + i + 5];
  54369. // 2D slope V1V4
  54370. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54371. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54372. // facet equations :
  54373. // we compute each facet normal vector
  54374. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54375. // we compute the value d by applying the equation to v1 which belongs to the plane
  54376. // then we store the facet equation in a Vector4
  54377. v2.subtractToRef(v1, v1v2);
  54378. v3.subtractToRef(v1, v1v3);
  54379. v4.subtractToRef(v1, v1v4);
  54380. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54381. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54382. norm1.normalize();
  54383. norm2.normalize();
  54384. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54385. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54386. var quad = this._heightQuads[row * subdivisionsX + col];
  54387. quad.slope.copyFromFloats(cd, h);
  54388. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54389. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54390. }
  54391. }
  54392. return this;
  54393. };
  54394. GroundMesh.prototype.serialize = function (serializationObject) {
  54395. _super.prototype.serialize.call(this, serializationObject);
  54396. serializationObject.subdivisionsX = this._subdivisionsX;
  54397. serializationObject.subdivisionsY = this._subdivisionsY;
  54398. serializationObject.minX = this._minX;
  54399. serializationObject.maxX = this._maxX;
  54400. serializationObject.minZ = this._minZ;
  54401. serializationObject.maxZ = this._maxZ;
  54402. serializationObject.width = this._width;
  54403. serializationObject.height = this._height;
  54404. };
  54405. GroundMesh.Parse = function (parsedMesh, scene) {
  54406. var result = new GroundMesh(parsedMesh.name, scene);
  54407. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54408. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54409. result._minX = parsedMesh.minX;
  54410. result._maxX = parsedMesh.maxX;
  54411. result._minZ = parsedMesh.minZ;
  54412. result._maxZ = parsedMesh.maxZ;
  54413. result._width = parsedMesh.width;
  54414. result._height = parsedMesh.height;
  54415. return result;
  54416. };
  54417. return GroundMesh;
  54418. }(BABYLON.Mesh));
  54419. BABYLON.GroundMesh = GroundMesh;
  54420. })(BABYLON || (BABYLON = {}));
  54421. //# sourceMappingURL=babylon.groundMesh.js.map
  54422. var BABYLON;
  54423. (function (BABYLON) {
  54424. /**
  54425. * Creates an instance based on a source mesh.
  54426. */
  54427. var InstancedMesh = /** @class */ (function (_super) {
  54428. __extends(InstancedMesh, _super);
  54429. function InstancedMesh(name, source) {
  54430. var _this = _super.call(this, name, source.getScene()) || this;
  54431. source.instances.push(_this);
  54432. _this._sourceMesh = source;
  54433. _this.position.copyFrom(source.position);
  54434. _this.rotation.copyFrom(source.rotation);
  54435. _this.scaling.copyFrom(source.scaling);
  54436. if (source.rotationQuaternion) {
  54437. _this.rotationQuaternion = source.rotationQuaternion.clone();
  54438. }
  54439. _this.infiniteDistance = source.infiniteDistance;
  54440. _this.setPivotMatrix(source.getPivotMatrix());
  54441. _this.refreshBoundingInfo();
  54442. _this._syncSubMeshes();
  54443. return _this;
  54444. }
  54445. /**
  54446. * Returns the string "InstancedMesh".
  54447. */
  54448. InstancedMesh.prototype.getClassName = function () {
  54449. return "InstancedMesh";
  54450. };
  54451. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  54452. // Methods
  54453. get: function () {
  54454. return this._sourceMesh.receiveShadows;
  54455. },
  54456. enumerable: true,
  54457. configurable: true
  54458. });
  54459. Object.defineProperty(InstancedMesh.prototype, "material", {
  54460. get: function () {
  54461. return this._sourceMesh.material;
  54462. },
  54463. enumerable: true,
  54464. configurable: true
  54465. });
  54466. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54467. get: function () {
  54468. return this._sourceMesh.visibility;
  54469. },
  54470. enumerable: true,
  54471. configurable: true
  54472. });
  54473. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54474. get: function () {
  54475. return this._sourceMesh.skeleton;
  54476. },
  54477. enumerable: true,
  54478. configurable: true
  54479. });
  54480. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54481. get: function () {
  54482. return this._sourceMesh.renderingGroupId;
  54483. },
  54484. enumerable: true,
  54485. configurable: true
  54486. });
  54487. /**
  54488. * Returns the total number of vertices (integer).
  54489. */
  54490. InstancedMesh.prototype.getTotalVertices = function () {
  54491. return this._sourceMesh.getTotalVertices();
  54492. };
  54493. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54494. get: function () {
  54495. return this._sourceMesh;
  54496. },
  54497. enumerable: true,
  54498. configurable: true
  54499. });
  54500. /**
  54501. * Is this node ready to be used/rendered
  54502. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54503. * @return {boolean} is it ready
  54504. */
  54505. InstancedMesh.prototype.isReady = function (completeCheck) {
  54506. if (completeCheck === void 0) { completeCheck = false; }
  54507. return this._sourceMesh.isReady(completeCheck, true);
  54508. };
  54509. /**
  54510. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54511. */
  54512. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54513. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54514. };
  54515. /**
  54516. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54517. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54518. * The `data` are either a numeric array either a Float32Array.
  54519. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54520. * 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).
  54521. * Note that a new underlying VertexBuffer object is created each call.
  54522. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54523. *
  54524. * Possible `kind` values :
  54525. * - BABYLON.VertexBuffer.PositionKind
  54526. * - BABYLON.VertexBuffer.UVKind
  54527. * - BABYLON.VertexBuffer.UV2Kind
  54528. * - BABYLON.VertexBuffer.UV3Kind
  54529. * - BABYLON.VertexBuffer.UV4Kind
  54530. * - BABYLON.VertexBuffer.UV5Kind
  54531. * - BABYLON.VertexBuffer.UV6Kind
  54532. * - BABYLON.VertexBuffer.ColorKind
  54533. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54534. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54535. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54536. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54537. *
  54538. * Returns the Mesh.
  54539. */
  54540. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54541. if (this.sourceMesh) {
  54542. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54543. }
  54544. return this.sourceMesh;
  54545. };
  54546. /**
  54547. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54548. * If the mesh has no geometry, it is simply returned as it is.
  54549. * The `data` are either a numeric array either a Float32Array.
  54550. * No new underlying VertexBuffer object is created.
  54551. * 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.
  54552. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54553. *
  54554. * Possible `kind` values :
  54555. * - BABYLON.VertexBuffer.PositionKind
  54556. * - BABYLON.VertexBuffer.UVKind
  54557. * - BABYLON.VertexBuffer.UV2Kind
  54558. * - BABYLON.VertexBuffer.UV3Kind
  54559. * - BABYLON.VertexBuffer.UV4Kind
  54560. * - BABYLON.VertexBuffer.UV5Kind
  54561. * - BABYLON.VertexBuffer.UV6Kind
  54562. * - BABYLON.VertexBuffer.ColorKind
  54563. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54564. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54565. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54566. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54567. *
  54568. * Returns the Mesh.
  54569. */
  54570. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54571. if (this.sourceMesh) {
  54572. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54573. }
  54574. return this.sourceMesh;
  54575. };
  54576. /**
  54577. * Sets the mesh indices.
  54578. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54579. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54580. * This method creates a new index buffer each call.
  54581. * Returns the Mesh.
  54582. */
  54583. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54584. if (totalVertices === void 0) { totalVertices = null; }
  54585. if (this.sourceMesh) {
  54586. this.sourceMesh.setIndices(indices, totalVertices);
  54587. }
  54588. return this.sourceMesh;
  54589. };
  54590. /**
  54591. * Boolean : True if the mesh owns the requested kind of data.
  54592. */
  54593. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  54594. return this._sourceMesh.isVerticesDataPresent(kind);
  54595. };
  54596. /**
  54597. * Returns an array of indices (IndicesArray).
  54598. */
  54599. InstancedMesh.prototype.getIndices = function () {
  54600. return this._sourceMesh.getIndices();
  54601. };
  54602. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  54603. get: function () {
  54604. return this._sourceMesh._positions;
  54605. },
  54606. enumerable: true,
  54607. configurable: true
  54608. });
  54609. /**
  54610. * Sets a new updated BoundingInfo to the mesh.
  54611. * Returns the mesh.
  54612. */
  54613. InstancedMesh.prototype.refreshBoundingInfo = function () {
  54614. var meshBB = this._sourceMesh.getBoundingInfo();
  54615. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  54616. this._updateBoundingInfo();
  54617. return this;
  54618. };
  54619. InstancedMesh.prototype._preActivate = function () {
  54620. if (this._currentLOD) {
  54621. this._currentLOD._preActivate();
  54622. }
  54623. return this;
  54624. };
  54625. InstancedMesh.prototype._activate = function (renderId) {
  54626. if (this._currentLOD) {
  54627. this._currentLOD._registerInstanceForRenderId(this, renderId);
  54628. }
  54629. return this;
  54630. };
  54631. /**
  54632. * Returns the current associated LOD AbstractMesh.
  54633. */
  54634. InstancedMesh.prototype.getLOD = function (camera) {
  54635. if (!camera) {
  54636. return this;
  54637. }
  54638. var boundingInfo = this.getBoundingInfo();
  54639. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  54640. if (this._currentLOD === this.sourceMesh) {
  54641. return this;
  54642. }
  54643. return this._currentLOD;
  54644. };
  54645. InstancedMesh.prototype._syncSubMeshes = function () {
  54646. this.releaseSubMeshes();
  54647. if (this._sourceMesh.subMeshes) {
  54648. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  54649. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  54650. }
  54651. }
  54652. return this;
  54653. };
  54654. InstancedMesh.prototype._generatePointsArray = function () {
  54655. return this._sourceMesh._generatePointsArray();
  54656. };
  54657. /**
  54658. * Creates a new InstancedMesh from the current mesh.
  54659. * - name (string) : the cloned mesh name
  54660. * - newParent (optional Node) : the optional Node to parent the clone to.
  54661. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  54662. *
  54663. * Returns the clone.
  54664. */
  54665. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54666. var result = this._sourceMesh.createInstance(name);
  54667. // Deep copy
  54668. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  54669. // Bounding info
  54670. this.refreshBoundingInfo();
  54671. // Parent
  54672. if (newParent) {
  54673. result.parent = newParent;
  54674. }
  54675. if (!doNotCloneChildren) {
  54676. // Children
  54677. for (var index = 0; index < this.getScene().meshes.length; index++) {
  54678. var mesh = this.getScene().meshes[index];
  54679. if (mesh.parent === this) {
  54680. mesh.clone(mesh.name, result);
  54681. }
  54682. }
  54683. }
  54684. result.computeWorldMatrix(true);
  54685. return result;
  54686. };
  54687. /**
  54688. * Disposes the InstancedMesh.
  54689. * Returns nothing.
  54690. */
  54691. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  54692. // Remove from mesh
  54693. var index = this._sourceMesh.instances.indexOf(this);
  54694. this._sourceMesh.instances.splice(index, 1);
  54695. _super.prototype.dispose.call(this, doNotRecurse);
  54696. };
  54697. return InstancedMesh;
  54698. }(BABYLON.AbstractMesh));
  54699. BABYLON.InstancedMesh = InstancedMesh;
  54700. })(BABYLON || (BABYLON = {}));
  54701. //# sourceMappingURL=babylon.instancedMesh.js.map
  54702. var BABYLON;
  54703. (function (BABYLON) {
  54704. var LinesMesh = /** @class */ (function (_super) {
  54705. __extends(LinesMesh, _super);
  54706. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  54707. if (scene === void 0) { scene = null; }
  54708. if (parent === void 0) { parent = null; }
  54709. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  54710. _this.useVertexColor = useVertexColor;
  54711. _this.useVertexAlpha = useVertexAlpha;
  54712. _this.color = new BABYLON.Color3(1, 1, 1);
  54713. _this.alpha = 1;
  54714. if (source) {
  54715. _this.color = source.color.clone();
  54716. _this.alpha = source.alpha;
  54717. _this.useVertexColor = source.useVertexColor;
  54718. _this.useVertexAlpha = source.useVertexAlpha;
  54719. }
  54720. _this._intersectionThreshold = 0.1;
  54721. var defines = [];
  54722. var options = {
  54723. attributes: [BABYLON.VertexBuffer.PositionKind],
  54724. uniforms: ["world", "viewProjection"],
  54725. needAlphaBlending: true,
  54726. defines: defines
  54727. };
  54728. if (useVertexAlpha === false) {
  54729. options.needAlphaBlending = false;
  54730. }
  54731. if (!useVertexColor) {
  54732. options.uniforms.push("color");
  54733. }
  54734. else {
  54735. options.defines.push("#define VERTEXCOLOR");
  54736. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  54737. }
  54738. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  54739. return _this;
  54740. }
  54741. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  54742. /**
  54743. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54744. * This margin is expressed in world space coordinates, so its value may vary.
  54745. * Default value is 0.1
  54746. * @returns the intersection Threshold value.
  54747. */
  54748. get: function () {
  54749. return this._intersectionThreshold;
  54750. },
  54751. /**
  54752. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54753. * This margin is expressed in world space coordinates, so its value may vary.
  54754. * @param value the new threshold to apply
  54755. */
  54756. set: function (value) {
  54757. if (this._intersectionThreshold === value) {
  54758. return;
  54759. }
  54760. this._intersectionThreshold = value;
  54761. if (this.geometry) {
  54762. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  54763. }
  54764. },
  54765. enumerable: true,
  54766. configurable: true
  54767. });
  54768. /**
  54769. * Returns the string "LineMesh"
  54770. */
  54771. LinesMesh.prototype.getClassName = function () {
  54772. return "LinesMesh";
  54773. };
  54774. Object.defineProperty(LinesMesh.prototype, "material", {
  54775. get: function () {
  54776. return this._colorShader;
  54777. },
  54778. set: function (value) {
  54779. // Do nothing
  54780. },
  54781. enumerable: true,
  54782. configurable: true
  54783. });
  54784. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  54785. get: function () {
  54786. return false;
  54787. },
  54788. enumerable: true,
  54789. configurable: true
  54790. });
  54791. LinesMesh.prototype.createInstance = function (name) {
  54792. throw new Error("LinesMeshes do not support createInstance.");
  54793. };
  54794. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  54795. if (!this._geometry) {
  54796. return this;
  54797. }
  54798. // VBOs
  54799. this._geometry._bind(this._colorShader.getEffect());
  54800. // Color
  54801. if (!this.useVertexColor) {
  54802. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  54803. }
  54804. return this;
  54805. };
  54806. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  54807. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  54808. return this;
  54809. }
  54810. var engine = this.getScene().getEngine();
  54811. // Draw order
  54812. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  54813. return this;
  54814. };
  54815. LinesMesh.prototype.dispose = function (doNotRecurse) {
  54816. this._colorShader.dispose();
  54817. _super.prototype.dispose.call(this, doNotRecurse);
  54818. };
  54819. /**
  54820. * Returns a new LineMesh object cloned from the current one.
  54821. */
  54822. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54823. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  54824. };
  54825. return LinesMesh;
  54826. }(BABYLON.Mesh));
  54827. BABYLON.LinesMesh = LinesMesh;
  54828. })(BABYLON || (BABYLON = {}));
  54829. //# sourceMappingURL=babylon.linesMesh.js.map
  54830. var BABYLON;
  54831. (function (BABYLON) {
  54832. var MeshBuilder = /** @class */ (function () {
  54833. function MeshBuilder() {
  54834. }
  54835. MeshBuilder.updateSideOrientation = function (orientation) {
  54836. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  54837. return BABYLON.Mesh.DOUBLESIDE;
  54838. }
  54839. if (orientation === undefined || orientation === null) {
  54840. return BABYLON.Mesh.FRONTSIDE;
  54841. }
  54842. return orientation;
  54843. };
  54844. /**
  54845. * Creates a box mesh.
  54846. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  54847. * The parameter `size` sets the size (float) of each box side (default 1).
  54848. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  54849. * 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).
  54850. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54851. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54852. * 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).
  54853. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54854. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54855. */
  54856. MeshBuilder.CreateBox = function (name, options, scene) {
  54857. if (scene === void 0) { scene = null; }
  54858. var box = new BABYLON.Mesh(name, scene);
  54859. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54860. box._originalBuilderSideOrientation = options.sideOrientation;
  54861. var vertexData = BABYLON.VertexData.CreateBox(options);
  54862. vertexData.applyToMesh(box, options.updatable);
  54863. return box;
  54864. };
  54865. /**
  54866. * Creates a sphere mesh.
  54867. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  54868. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  54869. * 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`).
  54870. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  54871. * 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
  54872. * 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).
  54873. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54874. * 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).
  54875. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54876. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54877. */
  54878. MeshBuilder.CreateSphere = function (name, options, scene) {
  54879. var sphere = new BABYLON.Mesh(name, scene);
  54880. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54881. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54882. var vertexData = BABYLON.VertexData.CreateSphere(options);
  54883. vertexData.applyToMesh(sphere, options.updatable);
  54884. return sphere;
  54885. };
  54886. /**
  54887. * Creates a plane polygonal mesh. By default, this is a disc.
  54888. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  54889. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  54890. * 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.
  54891. * 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
  54892. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54893. * 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).
  54894. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54895. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54896. */
  54897. MeshBuilder.CreateDisc = function (name, options, scene) {
  54898. if (scene === void 0) { scene = null; }
  54899. var disc = new BABYLON.Mesh(name, scene);
  54900. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54901. disc._originalBuilderSideOrientation = options.sideOrientation;
  54902. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54903. vertexData.applyToMesh(disc, options.updatable);
  54904. return disc;
  54905. };
  54906. /**
  54907. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  54908. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  54909. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  54910. * 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`).
  54911. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  54912. * 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.
  54913. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54914. * 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).
  54915. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54916. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54917. */
  54918. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54919. var sphere = new BABYLON.Mesh(name, scene);
  54920. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54921. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54922. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54923. vertexData.applyToMesh(sphere, options.updatable);
  54924. return sphere;
  54925. };
  54926. ;
  54927. /**
  54928. * Creates a ribbon mesh.
  54929. * 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.
  54930. *
  54931. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54932. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54933. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54934. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54935. * 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.
  54936. * 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.
  54937. * 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
  54938. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54939. * 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).
  54940. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54941. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54942. * 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.
  54943. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  54944. * 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
  54945. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  54946. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  54947. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54948. */
  54949. MeshBuilder.CreateRibbon = function (name, options, scene) {
  54950. if (scene === void 0) { scene = null; }
  54951. var pathArray = options.pathArray;
  54952. var closeArray = options.closeArray;
  54953. var closePath = options.closePath;
  54954. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54955. var instance = options.instance;
  54956. var updatable = options.updatable;
  54957. if (instance) {
  54958. // positionFunction : ribbon case
  54959. // only pathArray and sideOrientation parameters are taken into account for positions update
  54960. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  54961. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  54962. var positionFunction = function (positions) {
  54963. var minlg = pathArray[0].length;
  54964. var i = 0;
  54965. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  54966. for (var si = 1; si <= ns; si++) {
  54967. for (var p = 0; p < pathArray.length; p++) {
  54968. var path = pathArray[p];
  54969. var l = path.length;
  54970. minlg = (minlg < l) ? minlg : l;
  54971. var j = 0;
  54972. while (j < minlg) {
  54973. positions[i] = path[j].x;
  54974. positions[i + 1] = path[j].y;
  54975. positions[i + 2] = path[j].z;
  54976. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  54977. BABYLON.Tmp.Vector3[0].x = path[j].x;
  54978. }
  54979. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  54980. BABYLON.Tmp.Vector3[1].x = path[j].x;
  54981. }
  54982. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  54983. BABYLON.Tmp.Vector3[0].y = path[j].y;
  54984. }
  54985. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  54986. BABYLON.Tmp.Vector3[1].y = path[j].y;
  54987. }
  54988. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  54989. BABYLON.Tmp.Vector3[0].z = path[j].z;
  54990. }
  54991. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  54992. BABYLON.Tmp.Vector3[1].z = path[j].z;
  54993. }
  54994. j++;
  54995. i += 3;
  54996. }
  54997. if (instance._closePath) {
  54998. positions[i] = path[0].x;
  54999. positions[i + 1] = path[0].y;
  55000. positions[i + 2] = path[0].z;
  55001. i += 3;
  55002. }
  55003. }
  55004. }
  55005. };
  55006. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55007. positionFunction(positions);
  55008. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55009. instance._boundingInfo.update(instance._worldMatrix);
  55010. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55011. if (options.colors) {
  55012. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55013. for (var c = 0; c < options.colors.length; c++) {
  55014. colors[c * 4] = options.colors[c].r;
  55015. colors[c * 4 + 1] = options.colors[c].g;
  55016. colors[c * 4 + 2] = options.colors[c].b;
  55017. colors[c * 4 + 3] = options.colors[c].a;
  55018. }
  55019. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55020. }
  55021. if (options.uvs) {
  55022. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55023. for (var i = 0; i < options.uvs.length; i++) {
  55024. uvs[i * 2] = options.uvs[i].x;
  55025. uvs[i * 2 + 1] = options.uvs[i].y;
  55026. }
  55027. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55028. }
  55029. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55030. var indices = instance.getIndices();
  55031. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55032. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55033. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55034. if (instance._closePath) {
  55035. var indexFirst = 0;
  55036. var indexLast = 0;
  55037. for (var p = 0; p < pathArray.length; p++) {
  55038. indexFirst = instance._idx[p] * 3;
  55039. if (p + 1 < pathArray.length) {
  55040. indexLast = (instance._idx[p + 1] - 1) * 3;
  55041. }
  55042. else {
  55043. indexLast = normals.length - 3;
  55044. }
  55045. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55046. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55047. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55048. normals[indexLast] = normals[indexFirst];
  55049. normals[indexLast + 1] = normals[indexFirst + 1];
  55050. normals[indexLast + 2] = normals[indexFirst + 2];
  55051. }
  55052. }
  55053. if (!(instance.areNormalsFrozen)) {
  55054. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55055. }
  55056. }
  55057. return instance;
  55058. }
  55059. else {
  55060. var ribbon = new BABYLON.Mesh(name, scene);
  55061. ribbon._originalBuilderSideOrientation = sideOrientation;
  55062. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55063. if (closePath) {
  55064. ribbon._idx = vertexData._idx;
  55065. }
  55066. ribbon._closePath = closePath;
  55067. ribbon._closeArray = closeArray;
  55068. vertexData.applyToMesh(ribbon, updatable);
  55069. return ribbon;
  55070. }
  55071. };
  55072. /**
  55073. * Creates a cylinder or a cone mesh.
  55074. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55075. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55076. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55077. * 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.
  55078. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55079. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55080. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55081. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55082. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55083. * 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).
  55084. * 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
  55085. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55086. * 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
  55087. * 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.
  55088. * If `enclose` is false, a ring surface is one element.
  55089. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55090. * 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
  55091. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55092. * 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).
  55093. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55094. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55095. */
  55096. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55097. var cylinder = new BABYLON.Mesh(name, scene);
  55098. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55099. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55100. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55101. vertexData.applyToMesh(cylinder, options.updatable);
  55102. return cylinder;
  55103. };
  55104. /**
  55105. * Creates a torus mesh.
  55106. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55107. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55108. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55109. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55110. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55111. * 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).
  55112. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55113. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55114. */
  55115. MeshBuilder.CreateTorus = function (name, options, scene) {
  55116. var torus = new BABYLON.Mesh(name, scene);
  55117. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55118. torus._originalBuilderSideOrientation = options.sideOrientation;
  55119. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55120. vertexData.applyToMesh(torus, options.updatable);
  55121. return torus;
  55122. };
  55123. /**
  55124. * Creates a torus knot mesh.
  55125. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55126. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55127. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55128. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55129. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55130. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55131. * 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).
  55132. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55133. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55134. */
  55135. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55136. var torusKnot = new BABYLON.Mesh(name, scene);
  55137. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55138. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55139. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55140. vertexData.applyToMesh(torusKnot, options.updatable);
  55141. return torusKnot;
  55142. };
  55143. /**
  55144. * Creates a line system mesh.
  55145. * A line system is a pool of many lines gathered in a single mesh.
  55146. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55147. * 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.
  55148. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55149. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55150. * 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
  55151. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55152. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55153. * 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
  55154. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55155. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55156. */
  55157. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55158. var instance = options.instance;
  55159. var lines = options.lines;
  55160. var colors = options.colors;
  55161. if (instance) {
  55162. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55163. var vertexColor;
  55164. var lineColors;
  55165. if (colors) {
  55166. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55167. }
  55168. var i = 0;
  55169. var c = 0;
  55170. for (var l = 0; l < lines.length; l++) {
  55171. var points = lines[l];
  55172. for (var p = 0; p < points.length; p++) {
  55173. positions[i] = points[p].x;
  55174. positions[i + 1] = points[p].y;
  55175. positions[i + 2] = points[p].z;
  55176. if (colors && vertexColor) {
  55177. lineColors = colors[l];
  55178. vertexColor[c] = lineColors[p].r;
  55179. vertexColor[c + 1] = lineColors[p].g;
  55180. vertexColor[c + 2] = lineColors[p].b;
  55181. vertexColor[c + 3] = lineColors[p].a;
  55182. c += 4;
  55183. }
  55184. i += 3;
  55185. }
  55186. }
  55187. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55188. if (colors && vertexColor) {
  55189. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55190. }
  55191. return instance;
  55192. }
  55193. // line system creation
  55194. var useVertexColor = (colors) ? true : false;
  55195. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55196. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55197. vertexData.applyToMesh(lineSystem, options.updatable);
  55198. return lineSystem;
  55199. };
  55200. /**
  55201. * Creates a line mesh.
  55202. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55203. * 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.
  55204. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55205. * The parameter `points` is an array successive Vector3.
  55206. * 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
  55207. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55208. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55209. * When updating an instance, remember that only point positions can change, not the number of points.
  55210. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55211. */
  55212. MeshBuilder.CreateLines = function (name, options, scene) {
  55213. if (scene === void 0) { scene = null; }
  55214. var colors = (options.colors) ? [options.colors] : null;
  55215. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55216. return lines;
  55217. };
  55218. /**
  55219. * Creates a dashed line mesh.
  55220. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55221. * 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.
  55222. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55223. * The parameter `points` is an array successive Vector3.
  55224. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55225. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55226. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55227. * 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
  55228. * When updating an instance, remember that only point positions can change, not the number of points.
  55229. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55230. */
  55231. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55232. if (scene === void 0) { scene = null; }
  55233. var points = options.points;
  55234. var instance = options.instance;
  55235. var gapSize = options.gapSize || 1;
  55236. var dashSize = options.dashSize || 3;
  55237. if (instance) {
  55238. var positionFunction = function (positions) {
  55239. var curvect = BABYLON.Vector3.Zero();
  55240. var nbSeg = positions.length / 6;
  55241. var lg = 0;
  55242. var nb = 0;
  55243. var shft = 0;
  55244. var dashshft = 0;
  55245. var curshft = 0;
  55246. var p = 0;
  55247. var i = 0;
  55248. var j = 0;
  55249. for (i = 0; i < points.length - 1; i++) {
  55250. points[i + 1].subtractToRef(points[i], curvect);
  55251. lg += curvect.length();
  55252. }
  55253. shft = lg / nbSeg;
  55254. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55255. for (i = 0; i < points.length - 1; i++) {
  55256. points[i + 1].subtractToRef(points[i], curvect);
  55257. nb = Math.floor(curvect.length() / shft);
  55258. curvect.normalize();
  55259. j = 0;
  55260. while (j < nb && p < positions.length) {
  55261. curshft = shft * j;
  55262. positions[p] = points[i].x + curshft * curvect.x;
  55263. positions[p + 1] = points[i].y + curshft * curvect.y;
  55264. positions[p + 2] = points[i].z + curshft * curvect.z;
  55265. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55266. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55267. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55268. p += 6;
  55269. j++;
  55270. }
  55271. }
  55272. while (p < positions.length) {
  55273. positions[p] = points[i].x;
  55274. positions[p + 1] = points[i].y;
  55275. positions[p + 2] = points[i].z;
  55276. p += 3;
  55277. }
  55278. };
  55279. instance.updateMeshPositions(positionFunction, false);
  55280. return instance;
  55281. }
  55282. // dashed lines creation
  55283. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55284. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55285. vertexData.applyToMesh(dashedLines, options.updatable);
  55286. dashedLines.dashSize = dashSize;
  55287. dashedLines.gapSize = gapSize;
  55288. return dashedLines;
  55289. };
  55290. /**
  55291. * Creates an extruded shape mesh.
  55292. * 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.
  55293. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55294. *
  55295. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55296. * 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
  55297. * extruded along the Z axis.
  55298. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55299. * 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.
  55300. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55301. * 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
  55302. * 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
  55303. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55304. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55305. * 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).
  55306. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55307. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55308. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55309. */
  55310. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  55311. if (scene === void 0) { scene = null; }
  55312. var path = options.path;
  55313. var shape = options.shape;
  55314. var scale = options.scale || 1;
  55315. var rotation = options.rotation || 0;
  55316. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55317. var updatable = options.updatable;
  55318. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55319. var instance = options.instance || null;
  55320. var invertUV = options.invertUV || false;
  55321. 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);
  55322. };
  55323. /**
  55324. * Creates an custom extruded shape mesh.
  55325. * 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.
  55326. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  55327. *
  55328. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55329. * 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
  55330. * extruded along the Z axis.
  55331. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55332. * 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
  55333. * and the distance of this point from the begining of the path :
  55334. * ```javascript
  55335. * var rotationFunction = function(i, distance) {
  55336. * // do things
  55337. * return rotationValue; }
  55338. * ```
  55339. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55340. * 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
  55341. * and the distance of this point from the begining of the path :
  55342. * ```javascript
  55343. * var scaleFunction = function(i, distance) {
  55344. * // do things
  55345. * return scaleValue;}
  55346. * ```
  55347. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55348. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55349. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55350. * 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
  55351. * 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
  55352. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55353. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55354. * 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).
  55355. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55356. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55357. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55358. */
  55359. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  55360. var path = options.path;
  55361. var shape = options.shape;
  55362. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55363. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55364. var ribbonCloseArray = options.ribbonCloseArray || false;
  55365. var ribbonClosePath = options.ribbonClosePath || false;
  55366. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55367. var updatable = options.updatable;
  55368. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55369. var instance = options.instance;
  55370. var invertUV = options.invertUV || false;
  55371. 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);
  55372. };
  55373. /**
  55374. * Creates lathe mesh.
  55375. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55376. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55377. *
  55378. * 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
  55379. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55380. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55381. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55382. * 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.
  55383. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55384. * 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
  55385. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55386. * 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).
  55387. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55388. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55389. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55390. */
  55391. MeshBuilder.CreateLathe = function (name, options, scene) {
  55392. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55393. var closed = (options.closed === undefined) ? true : options.closed;
  55394. var shape = options.shape;
  55395. var radius = options.radius || 1;
  55396. var tessellation = options.tessellation || 64;
  55397. var updatable = options.updatable;
  55398. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55399. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55400. var pi2 = Math.PI * 2;
  55401. var paths = new Array();
  55402. var invertUV = options.invertUV || false;
  55403. var i = 0;
  55404. var p = 0;
  55405. var step = pi2 / tessellation * arc;
  55406. var rotated;
  55407. var path = new Array();
  55408. ;
  55409. for (i = 0; i <= tessellation; i++) {
  55410. var path = [];
  55411. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55412. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55413. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55414. }
  55415. for (p = 0; p < shape.length; p++) {
  55416. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55417. path.push(rotated);
  55418. }
  55419. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  55420. 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));
  55421. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  55422. }
  55423. paths.push(path);
  55424. }
  55425. // lathe ribbon
  55426. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55427. return lathe;
  55428. };
  55429. /**
  55430. * Creates a plane mesh.
  55431. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55432. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  55433. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  55434. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  55435. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55436. * 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).
  55437. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55438. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55439. */
  55440. MeshBuilder.CreatePlane = function (name, options, scene) {
  55441. var plane = new BABYLON.Mesh(name, scene);
  55442. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55443. plane._originalBuilderSideOrientation = options.sideOrientation;
  55444. var vertexData = BABYLON.VertexData.CreatePlane(options);
  55445. vertexData.applyToMesh(plane, options.updatable);
  55446. if (options.sourcePlane) {
  55447. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  55448. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  55449. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  55450. plane.rotate(vectorProduct, product);
  55451. }
  55452. return plane;
  55453. };
  55454. /**
  55455. * Creates a ground mesh.
  55456. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55457. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55458. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55459. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55460. */
  55461. MeshBuilder.CreateGround = function (name, options, scene) {
  55462. var ground = new BABYLON.GroundMesh(name, scene);
  55463. ground._setReady(false);
  55464. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55465. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55466. ground._width = options.width || 1;
  55467. ground._height = options.height || 1;
  55468. ground._maxX = ground._width / 2;
  55469. ground._maxZ = ground._height / 2;
  55470. ground._minX = -ground._maxX;
  55471. ground._minZ = -ground._maxZ;
  55472. var vertexData = BABYLON.VertexData.CreateGround(options);
  55473. vertexData.applyToMesh(ground, options.updatable);
  55474. ground._setReady(true);
  55475. return ground;
  55476. };
  55477. /**
  55478. * Creates a tiled ground mesh.
  55479. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55480. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55481. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55482. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55483. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55484. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55485. * numbers of subdivisions on the ground width and height of each tile.
  55486. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55487. */
  55488. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55489. var tiledGround = new BABYLON.Mesh(name, scene);
  55490. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55491. vertexData.applyToMesh(tiledGround, options.updatable);
  55492. return tiledGround;
  55493. };
  55494. /**
  55495. * Creates a ground mesh from a height map.
  55496. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55497. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55498. * The parameter `url` sets the URL of the height map image resource.
  55499. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55500. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55501. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55502. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55503. * 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.
  55504. * 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).
  55505. * This function is passed the newly built mesh :
  55506. * ```javascript
  55507. * function(mesh) { // do things
  55508. * return; }
  55509. * ```
  55510. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55511. */
  55512. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55513. var width = options.width || 10.0;
  55514. var height = options.height || 10.0;
  55515. var subdivisions = options.subdivisions || 1 | 0;
  55516. var minHeight = options.minHeight || 0.0;
  55517. var maxHeight = options.maxHeight || 1.0;
  55518. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55519. var updatable = options.updatable;
  55520. var onReady = options.onReady;
  55521. var ground = new BABYLON.GroundMesh(name, scene);
  55522. ground._subdivisionsX = subdivisions;
  55523. ground._subdivisionsY = subdivisions;
  55524. ground._width = width;
  55525. ground._height = height;
  55526. ground._maxX = ground._width / 2.0;
  55527. ground._maxZ = ground._height / 2.0;
  55528. ground._minX = -ground._maxX;
  55529. ground._minZ = -ground._maxZ;
  55530. ground._setReady(false);
  55531. var onload = function (img) {
  55532. // Getting height map data
  55533. var canvas = document.createElement("canvas");
  55534. var context = canvas.getContext("2d");
  55535. if (!context) {
  55536. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55537. }
  55538. if (scene.isDisposed) {
  55539. return;
  55540. }
  55541. var bufferWidth = img.width;
  55542. var bufferHeight = img.height;
  55543. canvas.width = bufferWidth;
  55544. canvas.height = bufferHeight;
  55545. context.drawImage(img, 0, 0);
  55546. // Create VertexData from map data
  55547. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55548. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55549. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55550. width: width, height: height,
  55551. subdivisions: subdivisions,
  55552. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55553. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55554. });
  55555. vertexData.applyToMesh(ground, updatable);
  55556. ground._setReady(true);
  55557. //execute ready callback, if set
  55558. if (onReady) {
  55559. onReady(ground);
  55560. }
  55561. };
  55562. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55563. return ground;
  55564. };
  55565. /**
  55566. * Creates a polygon mesh.
  55567. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55568. * 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.
  55569. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55570. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55571. * 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).
  55572. * Remember you can only change the shape positions, not their number when updating a polygon.
  55573. */
  55574. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55575. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55576. var shape = options.shape;
  55577. var holes = options.holes || [];
  55578. var depth = options.depth || 0;
  55579. var contours = [];
  55580. var hole = [];
  55581. for (var i = 0; i < shape.length; i++) {
  55582. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55583. }
  55584. var epsilon = 0.00000001;
  55585. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55586. contours.pop();
  55587. }
  55588. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55589. for (var hNb = 0; hNb < holes.length; hNb++) {
  55590. hole = [];
  55591. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  55592. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  55593. }
  55594. polygonTriangulation.addHole(hole);
  55595. }
  55596. var polygon = polygonTriangulation.build(options.updatable, depth);
  55597. polygon._originalBuilderSideOrientation = options.sideOrientation;
  55598. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  55599. vertexData.applyToMesh(polygon, options.updatable);
  55600. return polygon;
  55601. };
  55602. ;
  55603. /**
  55604. * Creates an extruded polygon mesh, with depth in the Y direction.
  55605. * 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).
  55606. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55607. */
  55608. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  55609. return MeshBuilder.CreatePolygon(name, options, scene);
  55610. };
  55611. ;
  55612. /**
  55613. * Creates a tube mesh.
  55614. * 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.
  55615. *
  55616. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  55617. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  55618. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  55619. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  55620. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  55621. * 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.
  55622. * It must return a radius value (positive float) :
  55623. * ```javascript
  55624. * var radiusFunction = function(i, distance) {
  55625. * // do things
  55626. * return radius; }
  55627. * ```
  55628. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  55629. * 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
  55630. * 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
  55631. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55632. * 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).
  55633. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55634. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55635. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55636. */
  55637. MeshBuilder.CreateTube = function (name, options, scene) {
  55638. var path = options.path;
  55639. var instance = options.instance;
  55640. var radius = 1.0;
  55641. if (instance) {
  55642. radius = instance.radius;
  55643. }
  55644. if (options.radius !== undefined) {
  55645. radius = options.radius;
  55646. }
  55647. ;
  55648. var tessellation = options.tessellation || 64 | 0;
  55649. var radiusFunction = options.radiusFunction || null;
  55650. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55651. var invertUV = options.invertUV || false;
  55652. var updatable = options.updatable;
  55653. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55654. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  55655. // tube geometry
  55656. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  55657. var tangents = path3D.getTangents();
  55658. var normals = path3D.getNormals();
  55659. var distances = path3D.getDistances();
  55660. var pi2 = Math.PI * 2;
  55661. var step = pi2 / tessellation * arc;
  55662. var returnRadius = function () { return radius; };
  55663. var radiusFunctionFinal = radiusFunction || returnRadius;
  55664. var circlePath;
  55665. var rad;
  55666. var normal;
  55667. var rotated;
  55668. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55669. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55670. for (var i = 0; i < path.length; i++) {
  55671. rad = radiusFunctionFinal(i, distances[i]); // current radius
  55672. circlePath = Array(); // current circle array
  55673. normal = normals[i]; // current normal
  55674. for (var t = 0; t < tessellation; t++) {
  55675. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  55676. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  55677. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  55678. rotated.scaleInPlace(rad).addInPlace(path[i]);
  55679. circlePath[t] = rotated;
  55680. }
  55681. circlePaths[index] = circlePath;
  55682. index++;
  55683. }
  55684. // cap
  55685. var capPath = function (nbPoints, pathIndex) {
  55686. var pointCap = Array();
  55687. for (var i = 0; i < nbPoints; i++) {
  55688. pointCap.push(path[pathIndex]);
  55689. }
  55690. return pointCap;
  55691. };
  55692. switch (cap) {
  55693. case BABYLON.Mesh.NO_CAP:
  55694. break;
  55695. case BABYLON.Mesh.CAP_START:
  55696. circlePaths[0] = capPath(tessellation, 0);
  55697. circlePaths[1] = circlePaths[2].slice(0);
  55698. break;
  55699. case BABYLON.Mesh.CAP_END:
  55700. circlePaths[index] = circlePaths[index - 1].slice(0);
  55701. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55702. break;
  55703. case BABYLON.Mesh.CAP_ALL:
  55704. circlePaths[0] = capPath(tessellation, 0);
  55705. circlePaths[1] = circlePaths[2].slice(0);
  55706. circlePaths[index] = circlePaths[index - 1].slice(0);
  55707. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55708. break;
  55709. default:
  55710. break;
  55711. }
  55712. return circlePaths;
  55713. };
  55714. var path3D;
  55715. var pathArray;
  55716. if (instance) {
  55717. var arc = options.arc || instance.arc;
  55718. path3D = (instance.path3D).update(path);
  55719. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  55720. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  55721. instance.path3D = path3D;
  55722. instance.pathArray = pathArray;
  55723. instance.arc = arc;
  55724. instance.radius = radius;
  55725. return instance;
  55726. }
  55727. // tube creation
  55728. path3D = new BABYLON.Path3D(path);
  55729. var newPathArray = new Array();
  55730. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55731. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  55732. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55733. tube.pathArray = pathArray;
  55734. tube.path3D = path3D;
  55735. tube.tessellation = tessellation;
  55736. tube.cap = cap;
  55737. tube.arc = options.arc;
  55738. tube.radius = radius;
  55739. return tube;
  55740. };
  55741. /**
  55742. * Creates a polyhedron mesh.
  55743. *
  55744. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  55745. * 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
  55746. * to choose the wanted type.
  55747. * The parameter `size` (positive float, default 1) sets the polygon size.
  55748. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  55749. * 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`.
  55750. * 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
  55751. * 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)`).
  55752. * 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
  55753. * 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.
  55754. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55755. * 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).
  55756. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55757. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55758. */
  55759. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  55760. var polyhedron = new BABYLON.Mesh(name, scene);
  55761. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55762. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  55763. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  55764. vertexData.applyToMesh(polyhedron, options.updatable);
  55765. return polyhedron;
  55766. };
  55767. /**
  55768. * Creates a decal mesh.
  55769. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  55770. * 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.
  55771. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  55772. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  55773. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  55774. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  55775. */
  55776. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  55777. var indices = sourceMesh.getIndices();
  55778. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55779. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55780. var position = options.position || BABYLON.Vector3.Zero();
  55781. var normal = options.normal || BABYLON.Vector3.Up();
  55782. var size = options.size || BABYLON.Vector3.One();
  55783. var angle = options.angle || 0;
  55784. // Getting correct rotation
  55785. if (!normal) {
  55786. var target = new BABYLON.Vector3(0, 0, 1);
  55787. var camera = sourceMesh.getScene().activeCamera;
  55788. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  55789. normal = camera.globalPosition.subtract(cameraWorldTarget);
  55790. }
  55791. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  55792. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  55793. var pitch = Math.atan2(normal.y, len);
  55794. // Matrix
  55795. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  55796. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  55797. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  55798. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  55799. var vertexData = new BABYLON.VertexData();
  55800. vertexData.indices = [];
  55801. vertexData.positions = [];
  55802. vertexData.normals = [];
  55803. vertexData.uvs = [];
  55804. var currentVertexDataIndex = 0;
  55805. var extractDecalVector3 = function (indexId) {
  55806. var result = new BABYLON.PositionNormalVertex();
  55807. if (!indices || !positions || !normals) {
  55808. return result;
  55809. }
  55810. var vertexId = indices[indexId];
  55811. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  55812. // Send vector to decal local world
  55813. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  55814. // Get normal
  55815. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  55816. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  55817. return result;
  55818. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  55819. var clip = function (vertices, axis) {
  55820. if (vertices.length === 0) {
  55821. return vertices;
  55822. }
  55823. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  55824. var clipVertices = function (v0, v1) {
  55825. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  55826. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  55827. };
  55828. var result = new Array();
  55829. for (var index = 0; index < vertices.length; index += 3) {
  55830. var v1Out;
  55831. var v2Out;
  55832. var v3Out;
  55833. var total = 0;
  55834. var nV1 = null;
  55835. var nV2 = null;
  55836. var nV3 = null;
  55837. var nV4 = null;
  55838. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  55839. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  55840. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  55841. v1Out = d1 > 0;
  55842. v2Out = d2 > 0;
  55843. v3Out = d3 > 0;
  55844. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  55845. switch (total) {
  55846. case 0:
  55847. result.push(vertices[index]);
  55848. result.push(vertices[index + 1]);
  55849. result.push(vertices[index + 2]);
  55850. break;
  55851. case 1:
  55852. if (v1Out) {
  55853. nV1 = vertices[index + 1];
  55854. nV2 = vertices[index + 2];
  55855. nV3 = clipVertices(vertices[index], nV1);
  55856. nV4 = clipVertices(vertices[index], nV2);
  55857. }
  55858. if (v2Out) {
  55859. nV1 = vertices[index];
  55860. nV2 = vertices[index + 2];
  55861. nV3 = clipVertices(vertices[index + 1], nV1);
  55862. nV4 = clipVertices(vertices[index + 1], nV2);
  55863. result.push(nV3);
  55864. result.push(nV2.clone());
  55865. result.push(nV1.clone());
  55866. result.push(nV2.clone());
  55867. result.push(nV3.clone());
  55868. result.push(nV4);
  55869. break;
  55870. }
  55871. if (v3Out) {
  55872. nV1 = vertices[index];
  55873. nV2 = vertices[index + 1];
  55874. nV3 = clipVertices(vertices[index + 2], nV1);
  55875. nV4 = clipVertices(vertices[index + 2], nV2);
  55876. }
  55877. if (nV1 && nV2 && nV3 && nV4) {
  55878. result.push(nV1.clone());
  55879. result.push(nV2.clone());
  55880. result.push(nV3);
  55881. result.push(nV4);
  55882. result.push(nV3.clone());
  55883. result.push(nV2.clone());
  55884. }
  55885. break;
  55886. case 2:
  55887. if (!v1Out) {
  55888. nV1 = vertices[index].clone();
  55889. nV2 = clipVertices(nV1, vertices[index + 1]);
  55890. nV3 = clipVertices(nV1, vertices[index + 2]);
  55891. result.push(nV1);
  55892. result.push(nV2);
  55893. result.push(nV3);
  55894. }
  55895. if (!v2Out) {
  55896. nV1 = vertices[index + 1].clone();
  55897. nV2 = clipVertices(nV1, vertices[index + 2]);
  55898. nV3 = clipVertices(nV1, vertices[index]);
  55899. result.push(nV1);
  55900. result.push(nV2);
  55901. result.push(nV3);
  55902. }
  55903. if (!v3Out) {
  55904. nV1 = vertices[index + 2].clone();
  55905. nV2 = clipVertices(nV1, vertices[index]);
  55906. nV3 = clipVertices(nV1, vertices[index + 1]);
  55907. result.push(nV1);
  55908. result.push(nV2);
  55909. result.push(nV3);
  55910. }
  55911. break;
  55912. case 3:
  55913. break;
  55914. }
  55915. }
  55916. return result;
  55917. };
  55918. for (var index = 0; index < indices.length; index += 3) {
  55919. var faceVertices = new Array();
  55920. faceVertices.push(extractDecalVector3(index));
  55921. faceVertices.push(extractDecalVector3(index + 1));
  55922. faceVertices.push(extractDecalVector3(index + 2));
  55923. // Clip
  55924. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55925. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55926. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55927. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55928. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55929. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55930. if (faceVertices.length === 0) {
  55931. continue;
  55932. }
  55933. // Add UVs and get back to world
  55934. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55935. var vertex = faceVertices[vIndex];
  55936. //TODO check for Int32Array | Uint32Array | Uint16Array
  55937. vertexData.indices.push(currentVertexDataIndex);
  55938. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55939. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55940. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55941. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  55942. currentVertexDataIndex++;
  55943. }
  55944. }
  55945. // Return mesh
  55946. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  55947. vertexData.applyToMesh(decal);
  55948. decal.position = position.clone();
  55949. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  55950. return decal;
  55951. };
  55952. // Privates
  55953. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  55954. // extrusion geometry
  55955. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  55956. var tangents = path3D.getTangents();
  55957. var normals = path3D.getNormals();
  55958. var binormals = path3D.getBinormals();
  55959. var distances = path3D.getDistances();
  55960. var angle = 0;
  55961. var returnScale = function () { return scale !== null ? scale : 1; };
  55962. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  55963. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  55964. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  55965. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55966. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55967. for (var i = 0; i < curve.length; i++) {
  55968. var shapePath = new Array();
  55969. var angleStep = rotate(i, distances[i]);
  55970. var scaleRatio = scl(i, distances[i]);
  55971. for (var p = 0; p < shape.length; p++) {
  55972. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  55973. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  55974. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  55975. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  55976. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  55977. shapePath[p] = rotated;
  55978. }
  55979. shapePaths[index] = shapePath;
  55980. angle += angleStep;
  55981. index++;
  55982. }
  55983. // cap
  55984. var capPath = function (shapePath) {
  55985. var pointCap = Array();
  55986. var barycenter = BABYLON.Vector3.Zero();
  55987. var i;
  55988. for (i = 0; i < shapePath.length; i++) {
  55989. barycenter.addInPlace(shapePath[i]);
  55990. }
  55991. barycenter.scaleInPlace(1.0 / shapePath.length);
  55992. for (i = 0; i < shapePath.length; i++) {
  55993. pointCap.push(barycenter);
  55994. }
  55995. return pointCap;
  55996. };
  55997. switch (cap) {
  55998. case BABYLON.Mesh.NO_CAP:
  55999. break;
  56000. case BABYLON.Mesh.CAP_START:
  56001. shapePaths[0] = capPath(shapePaths[2]);
  56002. shapePaths[1] = shapePaths[2];
  56003. break;
  56004. case BABYLON.Mesh.CAP_END:
  56005. shapePaths[index] = shapePaths[index - 1];
  56006. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56007. break;
  56008. case BABYLON.Mesh.CAP_ALL:
  56009. shapePaths[0] = capPath(shapePaths[2]);
  56010. shapePaths[1] = shapePaths[2];
  56011. shapePaths[index] = shapePaths[index - 1];
  56012. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56013. break;
  56014. default:
  56015. break;
  56016. }
  56017. return shapePaths;
  56018. };
  56019. var path3D;
  56020. var pathArray;
  56021. if (instance) {
  56022. path3D = (instance.path3D).update(curve);
  56023. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56024. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56025. return instance;
  56026. }
  56027. // extruded shape creation
  56028. path3D = new BABYLON.Path3D(curve);
  56029. var newShapePaths = new Array();
  56030. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56031. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56032. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56033. extrudedGeneric.pathArray = pathArray;
  56034. extrudedGeneric.path3D = path3D;
  56035. extrudedGeneric.cap = cap;
  56036. return extrudedGeneric;
  56037. };
  56038. return MeshBuilder;
  56039. }());
  56040. BABYLON.MeshBuilder = MeshBuilder;
  56041. })(BABYLON || (BABYLON = {}));
  56042. //# sourceMappingURL=babylon.meshBuilder.js.map
  56043. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  56044. var BABYLON;
  56045. (function (BABYLON) {
  56046. /**
  56047. * Draco compression (https://google.github.io/draco/)
  56048. */
  56049. var DracoCompression = /** @class */ (function () {
  56050. function DracoCompression() {
  56051. }
  56052. Object.defineProperty(DracoCompression, "IsSupported", {
  56053. /**
  56054. * Returns whether Draco compression is supported.
  56055. */
  56056. get: function () {
  56057. return BABYLON.Tools.IsWindowObjectExist() && !!window.DracoDecoderModule;
  56058. },
  56059. enumerable: true,
  56060. configurable: true
  56061. });
  56062. /**
  56063. * Decodes Draco compressed data to vertex data.
  56064. * @param data The array buffer view for the Draco compression data
  56065. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56066. * @returns The decoded vertex data
  56067. */
  56068. DracoCompression.Decode = function (data, attributes) {
  56069. var dracoModule = new DracoDecoderModule();
  56070. var buffer = new dracoModule.DecoderBuffer();
  56071. buffer.Init(data, data.byteLength);
  56072. var decoder = new dracoModule.Decoder();
  56073. var geometry;
  56074. var status;
  56075. var vertexData = new BABYLON.VertexData();
  56076. try {
  56077. var type = decoder.GetEncodedGeometryType(buffer);
  56078. switch (type) {
  56079. case dracoModule.TRIANGULAR_MESH:
  56080. geometry = new dracoModule.Mesh();
  56081. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56082. break;
  56083. case dracoModule.POINT_CLOUD:
  56084. geometry = new dracoModule.PointCloud();
  56085. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56086. break;
  56087. default:
  56088. throw new Error("Invalid geometry type " + type);
  56089. }
  56090. if (!status.ok() || !geometry.ptr) {
  56091. throw new Error(status.error_msg());
  56092. }
  56093. var numPoints = geometry.num_points();
  56094. if (type === dracoModule.TRIANGULAR_MESH) {
  56095. var numFaces = geometry.num_faces();
  56096. var faceIndices = new dracoModule.DracoInt32Array();
  56097. try {
  56098. vertexData.indices = new Uint32Array(numFaces * 3);
  56099. for (var i = 0; i < numFaces; i++) {
  56100. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56101. var offset = i * 3;
  56102. vertexData.indices[offset + 0] = faceIndices.GetValue(0);
  56103. vertexData.indices[offset + 1] = faceIndices.GetValue(1);
  56104. vertexData.indices[offset + 2] = faceIndices.GetValue(2);
  56105. }
  56106. }
  56107. finally {
  56108. dracoModule.destroy(faceIndices);
  56109. }
  56110. }
  56111. for (var kind in attributes) {
  56112. var uniqueId = attributes[kind];
  56113. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56114. var dracoData = new dracoModule.DracoFloat32Array();
  56115. try {
  56116. if (attribute.num_components() !== BABYLON.VertexBuffer.DeduceStride(kind)) {
  56117. throw new Error("Unsupported number of components for " + kind);
  56118. }
  56119. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56120. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56121. for (var i = 0; i < babylonData.length; i++) {
  56122. babylonData[i] = dracoData.GetValue(i);
  56123. }
  56124. vertexData.set(babylonData, kind);
  56125. }
  56126. finally {
  56127. dracoModule.destroy(dracoData);
  56128. }
  56129. }
  56130. }
  56131. finally {
  56132. if (geometry) {
  56133. dracoModule.destroy(geometry);
  56134. }
  56135. dracoModule.destroy(decoder);
  56136. dracoModule.destroy(buffer);
  56137. }
  56138. return vertexData;
  56139. };
  56140. return DracoCompression;
  56141. }());
  56142. BABYLON.DracoCompression = DracoCompression;
  56143. })(BABYLON || (BABYLON = {}));
  56144. //# sourceMappingURL=babylon.dracoCompression.js.map
  56145. var BABYLON;
  56146. (function (BABYLON) {
  56147. var AudioEngine = /** @class */ (function () {
  56148. function AudioEngine() {
  56149. this._audioContext = null;
  56150. this._audioContextInitialized = false;
  56151. this.canUseWebAudio = false;
  56152. this.WarnedWebAudioUnsupported = false;
  56153. this.unlocked = false;
  56154. this.isMP3supported = false;
  56155. this.isOGGsupported = false;
  56156. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56157. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56158. this.canUseWebAudio = true;
  56159. }
  56160. var audioElem = document.createElement('audio');
  56161. try {
  56162. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56163. this.isMP3supported = true;
  56164. }
  56165. }
  56166. catch (e) {
  56167. // protect error during capability check.
  56168. }
  56169. try {
  56170. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56171. this.isOGGsupported = true;
  56172. }
  56173. }
  56174. catch (e) {
  56175. // protect error during capability check.
  56176. }
  56177. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56178. this._unlockiOSaudio();
  56179. }
  56180. else {
  56181. this.unlocked = true;
  56182. }
  56183. }
  56184. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56185. get: function () {
  56186. if (!this._audioContextInitialized) {
  56187. this._initializeAudioContext();
  56188. }
  56189. return this._audioContext;
  56190. },
  56191. enumerable: true,
  56192. configurable: true
  56193. });
  56194. AudioEngine.prototype._unlockiOSaudio = function () {
  56195. var _this = this;
  56196. var unlockaudio = function () {
  56197. if (!_this.audioContext) {
  56198. return;
  56199. }
  56200. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56201. var source = _this.audioContext.createBufferSource();
  56202. source.buffer = buffer;
  56203. source.connect(_this.audioContext.destination);
  56204. source.start(0);
  56205. setTimeout(function () {
  56206. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56207. _this.unlocked = true;
  56208. window.removeEventListener('touchend', unlockaudio, false);
  56209. if (_this.onAudioUnlocked) {
  56210. _this.onAudioUnlocked();
  56211. }
  56212. }
  56213. }, 0);
  56214. };
  56215. window.addEventListener('touchend', unlockaudio, false);
  56216. };
  56217. AudioEngine.prototype._initializeAudioContext = function () {
  56218. try {
  56219. if (this.canUseWebAudio) {
  56220. this._audioContext = new AudioContext();
  56221. // create a global volume gain node
  56222. this.masterGain = this._audioContext.createGain();
  56223. this.masterGain.gain.value = 1;
  56224. this.masterGain.connect(this._audioContext.destination);
  56225. this._audioContextInitialized = true;
  56226. }
  56227. }
  56228. catch (e) {
  56229. this.canUseWebAudio = false;
  56230. BABYLON.Tools.Error("Web Audio: " + e.message);
  56231. }
  56232. };
  56233. AudioEngine.prototype.dispose = function () {
  56234. if (this.canUseWebAudio && this._audioContextInitialized) {
  56235. if (this._connectedAnalyser && this._audioContext) {
  56236. this._connectedAnalyser.stopDebugCanvas();
  56237. this._connectedAnalyser.dispose();
  56238. this.masterGain.disconnect();
  56239. this.masterGain.connect(this._audioContext.destination);
  56240. this._connectedAnalyser = null;
  56241. }
  56242. this.masterGain.gain.value = 1;
  56243. }
  56244. this.WarnedWebAudioUnsupported = false;
  56245. };
  56246. AudioEngine.prototype.getGlobalVolume = function () {
  56247. if (this.canUseWebAudio && this._audioContextInitialized) {
  56248. return this.masterGain.gain.value;
  56249. }
  56250. else {
  56251. return -1;
  56252. }
  56253. };
  56254. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  56255. if (this.canUseWebAudio && this._audioContextInitialized) {
  56256. this.masterGain.gain.value = newVolume;
  56257. }
  56258. };
  56259. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  56260. if (this._connectedAnalyser) {
  56261. this._connectedAnalyser.stopDebugCanvas();
  56262. }
  56263. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  56264. this._connectedAnalyser = analyser;
  56265. this.masterGain.disconnect();
  56266. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56267. }
  56268. };
  56269. return AudioEngine;
  56270. }());
  56271. BABYLON.AudioEngine = AudioEngine;
  56272. })(BABYLON || (BABYLON = {}));
  56273. //# sourceMappingURL=babylon.audioEngine.js.map
  56274. var BABYLON;
  56275. (function (BABYLON) {
  56276. var Sound = /** @class */ (function () {
  56277. /**
  56278. * Create a sound and attach it to a scene
  56279. * @param name Name of your sound
  56280. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56281. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56282. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56283. */
  56284. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56285. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56286. var _this = this;
  56287. this.autoplay = false;
  56288. this.loop = false;
  56289. this.useCustomAttenuation = false;
  56290. this.spatialSound = false;
  56291. this.refDistance = 1;
  56292. this.rolloffFactor = 1;
  56293. this.maxDistance = 100;
  56294. this.distanceModel = "linear";
  56295. this._panningModel = "equalpower";
  56296. this._playbackRate = 1;
  56297. this._streaming = false;
  56298. this._startTime = 0;
  56299. this._startOffset = 0;
  56300. this._position = BABYLON.Vector3.Zero();
  56301. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56302. this._volume = 1;
  56303. this._isReadyToPlay = false;
  56304. this.isPlaying = false;
  56305. this.isPaused = false;
  56306. this._isDirectional = false;
  56307. // Used if you'd like to create a directional sound.
  56308. // If not set, the sound will be omnidirectional
  56309. this._coneInnerAngle = 360;
  56310. this._coneOuterAngle = 360;
  56311. this._coneOuterGain = 0;
  56312. this._isOutputConnected = false;
  56313. this._urlType = "Unknown";
  56314. this.name = name;
  56315. this._scene = scene;
  56316. this._readyToPlayCallback = readyToPlayCallback;
  56317. // Default custom attenuation function is a linear attenuation
  56318. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56319. if (currentDistance < maxDistance) {
  56320. return currentVolume * (1 - currentDistance / maxDistance);
  56321. }
  56322. else {
  56323. return 0;
  56324. }
  56325. };
  56326. if (options) {
  56327. this.autoplay = options.autoplay || false;
  56328. this.loop = options.loop || false;
  56329. // if volume === 0, we need another way to check this option
  56330. if (options.volume !== undefined) {
  56331. this._volume = options.volume;
  56332. }
  56333. this.spatialSound = options.spatialSound || false;
  56334. this.maxDistance = options.maxDistance || 100;
  56335. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56336. this.rolloffFactor = options.rolloffFactor || 1;
  56337. this.refDistance = options.refDistance || 1;
  56338. this.distanceModel = options.distanceModel || "linear";
  56339. this._playbackRate = options.playbackRate || 1;
  56340. this._streaming = options.streaming || false;
  56341. }
  56342. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56343. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  56344. this._soundGain.gain.value = this._volume;
  56345. this._inputAudioNode = this._soundGain;
  56346. this._ouputAudioNode = this._soundGain;
  56347. if (this.spatialSound) {
  56348. this._createSpatialParameters();
  56349. }
  56350. this._scene.mainSoundTrack.AddSound(this);
  56351. var validParameter = true;
  56352. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  56353. if (urlOrArrayBuffer) {
  56354. if (typeof (urlOrArrayBuffer) === "string")
  56355. this._urlType = "String";
  56356. if (Array.isArray(urlOrArrayBuffer))
  56357. this._urlType = "Array";
  56358. if (urlOrArrayBuffer instanceof ArrayBuffer)
  56359. this._urlType = "ArrayBuffer";
  56360. var urls = [];
  56361. var codecSupportedFound = false;
  56362. switch (this._urlType) {
  56363. case "ArrayBuffer":
  56364. if (urlOrArrayBuffer.byteLength > 0) {
  56365. codecSupportedFound = true;
  56366. this._soundLoaded(urlOrArrayBuffer);
  56367. }
  56368. break;
  56369. case "String":
  56370. urls.push(urlOrArrayBuffer);
  56371. case "Array":
  56372. if (urls.length === 0)
  56373. urls = urlOrArrayBuffer;
  56374. // If we found a supported format, we load it immediately and stop the loop
  56375. for (var i = 0; i < urls.length; i++) {
  56376. var url = urls[i];
  56377. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  56378. codecSupportedFound = true;
  56379. }
  56380. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  56381. codecSupportedFound = true;
  56382. }
  56383. if (url.indexOf(".wav", url.length - 4) !== -1) {
  56384. codecSupportedFound = true;
  56385. }
  56386. if (url.indexOf("blob:") !== -1) {
  56387. codecSupportedFound = true;
  56388. }
  56389. if (codecSupportedFound) {
  56390. // Loading sound using XHR2
  56391. if (!this._streaming) {
  56392. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  56393. }
  56394. else {
  56395. this._htmlAudioElement = new Audio(url);
  56396. this._htmlAudioElement.controls = false;
  56397. this._htmlAudioElement.loop = this.loop;
  56398. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  56399. this._htmlAudioElement.preload = "auto";
  56400. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  56401. _this._isReadyToPlay = true;
  56402. if (_this.autoplay) {
  56403. _this.play();
  56404. }
  56405. if (_this._readyToPlayCallback) {
  56406. _this._readyToPlayCallback();
  56407. }
  56408. });
  56409. document.body.appendChild(this._htmlAudioElement);
  56410. }
  56411. break;
  56412. }
  56413. }
  56414. break;
  56415. default:
  56416. validParameter = false;
  56417. break;
  56418. }
  56419. if (!validParameter) {
  56420. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  56421. }
  56422. else {
  56423. if (!codecSupportedFound) {
  56424. this._isReadyToPlay = true;
  56425. // Simulating a ready to play event to avoid breaking code path
  56426. if (this._readyToPlayCallback) {
  56427. window.setTimeout(function () {
  56428. if (_this._readyToPlayCallback) {
  56429. _this._readyToPlayCallback();
  56430. }
  56431. }, 1000);
  56432. }
  56433. }
  56434. }
  56435. }
  56436. }
  56437. else {
  56438. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  56439. this._scene.mainSoundTrack.AddSound(this);
  56440. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  56441. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  56442. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  56443. }
  56444. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  56445. if (this._readyToPlayCallback) {
  56446. window.setTimeout(function () {
  56447. if (_this._readyToPlayCallback) {
  56448. _this._readyToPlayCallback();
  56449. }
  56450. }, 1000);
  56451. }
  56452. }
  56453. }
  56454. Sound.prototype.dispose = function () {
  56455. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  56456. if (this.isPlaying) {
  56457. this.stop();
  56458. }
  56459. this._isReadyToPlay = false;
  56460. if (this.soundTrackId === -1) {
  56461. this._scene.mainSoundTrack.RemoveSound(this);
  56462. }
  56463. else {
  56464. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  56465. }
  56466. if (this._soundGain) {
  56467. this._soundGain.disconnect();
  56468. this._soundGain = null;
  56469. }
  56470. if (this._soundPanner) {
  56471. this._soundPanner.disconnect();
  56472. this._soundPanner = null;
  56473. }
  56474. if (this._soundSource) {
  56475. this._soundSource.disconnect();
  56476. this._soundSource = null;
  56477. }
  56478. this._audioBuffer = null;
  56479. if (this._htmlAudioElement) {
  56480. this._htmlAudioElement.pause();
  56481. this._htmlAudioElement.src = "";
  56482. document.body.removeChild(this._htmlAudioElement);
  56483. }
  56484. if (this._connectedMesh && this._registerFunc) {
  56485. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56486. this._connectedMesh = null;
  56487. }
  56488. }
  56489. };
  56490. Sound.prototype.isReady = function () {
  56491. return this._isReadyToPlay;
  56492. };
  56493. Sound.prototype._soundLoaded = function (audioData) {
  56494. var _this = this;
  56495. if (!BABYLON.Engine.audioEngine.audioContext) {
  56496. return;
  56497. }
  56498. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  56499. _this._audioBuffer = buffer;
  56500. _this._isReadyToPlay = true;
  56501. if (_this.autoplay) {
  56502. _this.play();
  56503. }
  56504. if (_this._readyToPlayCallback) {
  56505. _this._readyToPlayCallback();
  56506. }
  56507. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  56508. };
  56509. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  56510. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56511. this._audioBuffer = audioBuffer;
  56512. this._isReadyToPlay = true;
  56513. }
  56514. };
  56515. Sound.prototype.updateOptions = function (options) {
  56516. if (options) {
  56517. this.loop = options.loop || this.loop;
  56518. this.maxDistance = options.maxDistance || this.maxDistance;
  56519. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  56520. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  56521. this.refDistance = options.refDistance || this.refDistance;
  56522. this.distanceModel = options.distanceModel || this.distanceModel;
  56523. this._playbackRate = options.playbackRate || this._playbackRate;
  56524. this._updateSpatialParameters();
  56525. if (this.isPlaying) {
  56526. if (this._streaming) {
  56527. this._htmlAudioElement.playbackRate = this._playbackRate;
  56528. }
  56529. else {
  56530. if (this._soundSource) {
  56531. this._soundSource.playbackRate.value = this._playbackRate;
  56532. }
  56533. }
  56534. }
  56535. }
  56536. };
  56537. Sound.prototype._createSpatialParameters = function () {
  56538. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56539. if (this._scene.headphone) {
  56540. this._panningModel = "HRTF";
  56541. }
  56542. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  56543. this._updateSpatialParameters();
  56544. this._soundPanner.connect(this._ouputAudioNode);
  56545. this._inputAudioNode = this._soundPanner;
  56546. }
  56547. };
  56548. Sound.prototype._updateSpatialParameters = function () {
  56549. if (this.spatialSound && this._soundPanner) {
  56550. if (this.useCustomAttenuation) {
  56551. // Tricks to disable in a way embedded Web Audio attenuation
  56552. this._soundPanner.distanceModel = "linear";
  56553. this._soundPanner.maxDistance = Number.MAX_VALUE;
  56554. this._soundPanner.refDistance = 1;
  56555. this._soundPanner.rolloffFactor = 1;
  56556. this._soundPanner.panningModel = this._panningModel;
  56557. }
  56558. else {
  56559. this._soundPanner.distanceModel = this.distanceModel;
  56560. this._soundPanner.maxDistance = this.maxDistance;
  56561. this._soundPanner.refDistance = this.refDistance;
  56562. this._soundPanner.rolloffFactor = this.rolloffFactor;
  56563. this._soundPanner.panningModel = this._panningModel;
  56564. }
  56565. }
  56566. };
  56567. Sound.prototype.switchPanningModelToHRTF = function () {
  56568. this._panningModel = "HRTF";
  56569. this._switchPanningModel();
  56570. };
  56571. Sound.prototype.switchPanningModelToEqualPower = function () {
  56572. this._panningModel = "equalpower";
  56573. this._switchPanningModel();
  56574. };
  56575. Sound.prototype._switchPanningModel = function () {
  56576. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56577. this._soundPanner.panningModel = this._panningModel;
  56578. }
  56579. };
  56580. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  56581. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56582. if (this._isOutputConnected) {
  56583. this._ouputAudioNode.disconnect();
  56584. }
  56585. this._ouputAudioNode.connect(soundTrackAudioNode);
  56586. this._isOutputConnected = true;
  56587. }
  56588. };
  56589. /**
  56590. * Transform this sound into a directional source
  56591. * @param coneInnerAngle Size of the inner cone in degree
  56592. * @param coneOuterAngle Size of the outer cone in degree
  56593. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  56594. */
  56595. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  56596. if (coneOuterAngle < coneInnerAngle) {
  56597. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  56598. return;
  56599. }
  56600. this._coneInnerAngle = coneInnerAngle;
  56601. this._coneOuterAngle = coneOuterAngle;
  56602. this._coneOuterGain = coneOuterGain;
  56603. this._isDirectional = true;
  56604. if (this.isPlaying && this.loop) {
  56605. this.stop();
  56606. this.play();
  56607. }
  56608. };
  56609. Sound.prototype.setPosition = function (newPosition) {
  56610. this._position = newPosition;
  56611. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56612. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56613. }
  56614. };
  56615. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  56616. this._localDirection = newLocalDirection;
  56617. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  56618. this._updateDirection();
  56619. }
  56620. };
  56621. Sound.prototype._updateDirection = function () {
  56622. if (!this._connectedMesh || !this._soundPanner) {
  56623. return;
  56624. }
  56625. var mat = this._connectedMesh.getWorldMatrix();
  56626. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  56627. direction.normalize();
  56628. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  56629. };
  56630. Sound.prototype.updateDistanceFromListener = function () {
  56631. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  56632. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  56633. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  56634. }
  56635. };
  56636. Sound.prototype.setAttenuationFunction = function (callback) {
  56637. this._customAttenuationFunction = callback;
  56638. };
  56639. /**
  56640. * Play the sound
  56641. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  56642. * @param offset (optional) Start the sound setting it at a specific time
  56643. */
  56644. Sound.prototype.play = function (time, offset) {
  56645. var _this = this;
  56646. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  56647. try {
  56648. if (this._startOffset < 0) {
  56649. time = -this._startOffset;
  56650. this._startOffset = 0;
  56651. }
  56652. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56653. if (!this._soundSource || !this._streamingSource) {
  56654. if (this.spatialSound && this._soundPanner) {
  56655. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56656. if (this._isDirectional) {
  56657. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  56658. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  56659. this._soundPanner.coneOuterGain = this._coneOuterGain;
  56660. if (this._connectedMesh) {
  56661. this._updateDirection();
  56662. }
  56663. else {
  56664. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  56665. }
  56666. }
  56667. }
  56668. }
  56669. if (this._streaming) {
  56670. if (!this._streamingSource) {
  56671. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  56672. this._htmlAudioElement.onended = function () { _this._onended(); };
  56673. this._htmlAudioElement.playbackRate = this._playbackRate;
  56674. }
  56675. this._streamingSource.disconnect();
  56676. this._streamingSource.connect(this._inputAudioNode);
  56677. this._htmlAudioElement.play();
  56678. }
  56679. else {
  56680. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  56681. this._soundSource.buffer = this._audioBuffer;
  56682. this._soundSource.connect(this._inputAudioNode);
  56683. this._soundSource.loop = this.loop;
  56684. this._soundSource.playbackRate.value = this._playbackRate;
  56685. this._soundSource.onended = function () { _this._onended(); };
  56686. if (this._soundSource.buffer) {
  56687. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  56688. }
  56689. }
  56690. this._startTime = startTime;
  56691. this.isPlaying = true;
  56692. this.isPaused = false;
  56693. }
  56694. catch (ex) {
  56695. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  56696. }
  56697. }
  56698. };
  56699. Sound.prototype._onended = function () {
  56700. this.isPlaying = false;
  56701. if (this.onended) {
  56702. this.onended();
  56703. }
  56704. };
  56705. /**
  56706. * Stop the sound
  56707. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  56708. */
  56709. Sound.prototype.stop = function (time) {
  56710. if (this.isPlaying) {
  56711. if (this._streaming) {
  56712. this._htmlAudioElement.pause();
  56713. // Test needed for Firefox or it will generate an Invalid State Error
  56714. if (this._htmlAudioElement.currentTime > 0) {
  56715. this._htmlAudioElement.currentTime = 0;
  56716. }
  56717. }
  56718. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  56719. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56720. this._soundSource.stop(stopTime);
  56721. this._soundSource.onended = function () { };
  56722. if (!this.isPaused) {
  56723. this._startOffset = 0;
  56724. }
  56725. }
  56726. this.isPlaying = false;
  56727. }
  56728. };
  56729. Sound.prototype.pause = function () {
  56730. if (this.isPlaying) {
  56731. this.isPaused = true;
  56732. if (this._streaming) {
  56733. this._htmlAudioElement.pause();
  56734. }
  56735. else if (BABYLON.Engine.audioEngine.audioContext) {
  56736. this.stop(0);
  56737. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  56738. }
  56739. }
  56740. };
  56741. Sound.prototype.setVolume = function (newVolume, time) {
  56742. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  56743. if (time && BABYLON.Engine.audioEngine.audioContext) {
  56744. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  56745. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  56746. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  56747. }
  56748. else {
  56749. this._soundGain.gain.value = newVolume;
  56750. }
  56751. }
  56752. this._volume = newVolume;
  56753. };
  56754. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  56755. this._playbackRate = newPlaybackRate;
  56756. if (this.isPlaying) {
  56757. if (this._streaming) {
  56758. this._htmlAudioElement.playbackRate = this._playbackRate;
  56759. }
  56760. else if (this._soundSource) {
  56761. this._soundSource.playbackRate.value = this._playbackRate;
  56762. }
  56763. }
  56764. };
  56765. Sound.prototype.getVolume = function () {
  56766. return this._volume;
  56767. };
  56768. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  56769. var _this = this;
  56770. if (this._connectedMesh && this._registerFunc) {
  56771. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56772. this._registerFunc = null;
  56773. }
  56774. this._connectedMesh = meshToConnectTo;
  56775. if (!this.spatialSound) {
  56776. this.spatialSound = true;
  56777. this._createSpatialParameters();
  56778. if (this.isPlaying && this.loop) {
  56779. this.stop();
  56780. this.play();
  56781. }
  56782. }
  56783. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  56784. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  56785. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  56786. };
  56787. Sound.prototype.detachFromMesh = function () {
  56788. if (this._connectedMesh && this._registerFunc) {
  56789. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56790. this._registerFunc = null;
  56791. this._connectedMesh = null;
  56792. }
  56793. };
  56794. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  56795. if (!node.getBoundingInfo) {
  56796. return;
  56797. }
  56798. var mesh = node;
  56799. var boundingInfo = mesh.getBoundingInfo();
  56800. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  56801. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  56802. this._updateDirection();
  56803. }
  56804. };
  56805. Sound.prototype.clone = function () {
  56806. var _this = this;
  56807. if (!this._streaming) {
  56808. var setBufferAndRun = function () {
  56809. if (_this._isReadyToPlay) {
  56810. clonedSound._audioBuffer = _this.getAudioBuffer();
  56811. clonedSound._isReadyToPlay = true;
  56812. if (clonedSound.autoplay) {
  56813. clonedSound.play();
  56814. }
  56815. }
  56816. else {
  56817. window.setTimeout(setBufferAndRun, 300);
  56818. }
  56819. };
  56820. var currentOptions = {
  56821. autoplay: this.autoplay, loop: this.loop,
  56822. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  56823. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  56824. refDistance: this.refDistance, distanceModel: this.distanceModel
  56825. };
  56826. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  56827. if (this.useCustomAttenuation) {
  56828. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  56829. }
  56830. clonedSound.setPosition(this._position);
  56831. clonedSound.setPlaybackRate(this._playbackRate);
  56832. setBufferAndRun();
  56833. return clonedSound;
  56834. }
  56835. else {
  56836. return null;
  56837. }
  56838. };
  56839. Sound.prototype.getAudioBuffer = function () {
  56840. return this._audioBuffer;
  56841. };
  56842. Sound.prototype.serialize = function () {
  56843. var serializationObject = {
  56844. name: this.name,
  56845. url: this.name,
  56846. autoplay: this.autoplay,
  56847. loop: this.loop,
  56848. volume: this._volume,
  56849. spatialSound: this.spatialSound,
  56850. maxDistance: this.maxDistance,
  56851. rolloffFactor: this.rolloffFactor,
  56852. refDistance: this.refDistance,
  56853. distanceModel: this.distanceModel,
  56854. playbackRate: this._playbackRate,
  56855. panningModel: this._panningModel,
  56856. soundTrackId: this.soundTrackId
  56857. };
  56858. if (this.spatialSound) {
  56859. if (this._connectedMesh)
  56860. serializationObject.connectedMeshId = this._connectedMesh.id;
  56861. serializationObject.position = this._position.asArray();
  56862. serializationObject.refDistance = this.refDistance;
  56863. serializationObject.distanceModel = this.distanceModel;
  56864. serializationObject.isDirectional = this._isDirectional;
  56865. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  56866. serializationObject.coneInnerAngle = this._coneInnerAngle;
  56867. serializationObject.coneOuterAngle = this._coneOuterAngle;
  56868. serializationObject.coneOuterGain = this._coneOuterGain;
  56869. }
  56870. return serializationObject;
  56871. };
  56872. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  56873. var soundName = parsedSound.name;
  56874. var soundUrl;
  56875. if (parsedSound.url) {
  56876. soundUrl = rootUrl + parsedSound.url;
  56877. }
  56878. else {
  56879. soundUrl = rootUrl + soundName;
  56880. }
  56881. var options = {
  56882. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  56883. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  56884. rolloffFactor: parsedSound.rolloffFactor,
  56885. refDistance: parsedSound.refDistance,
  56886. distanceModel: parsedSound.distanceModel,
  56887. playbackRate: parsedSound.playbackRate
  56888. };
  56889. var newSound;
  56890. if (!sourceSound) {
  56891. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  56892. scene._addPendingData(newSound);
  56893. }
  56894. else {
  56895. var setBufferAndRun = function () {
  56896. if (sourceSound._isReadyToPlay) {
  56897. newSound._audioBuffer = sourceSound.getAudioBuffer();
  56898. newSound._isReadyToPlay = true;
  56899. if (newSound.autoplay) {
  56900. newSound.play();
  56901. }
  56902. }
  56903. else {
  56904. window.setTimeout(setBufferAndRun, 300);
  56905. }
  56906. };
  56907. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  56908. setBufferAndRun();
  56909. }
  56910. if (parsedSound.position) {
  56911. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  56912. newSound.setPosition(soundPosition);
  56913. }
  56914. if (parsedSound.isDirectional) {
  56915. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  56916. if (parsedSound.localDirectionToMesh) {
  56917. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  56918. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  56919. }
  56920. }
  56921. if (parsedSound.connectedMeshId) {
  56922. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  56923. if (connectedMesh) {
  56924. newSound.attachToMesh(connectedMesh);
  56925. }
  56926. }
  56927. return newSound;
  56928. };
  56929. return Sound;
  56930. }());
  56931. BABYLON.Sound = Sound;
  56932. })(BABYLON || (BABYLON = {}));
  56933. //# sourceMappingURL=babylon.sound.js.map
  56934. var BABYLON;
  56935. (function (BABYLON) {
  56936. var SoundTrack = /** @class */ (function () {
  56937. function SoundTrack(scene, options) {
  56938. this.id = -1;
  56939. this._isMainTrack = false;
  56940. this._isInitialized = false;
  56941. this._scene = scene;
  56942. this.soundCollection = new Array();
  56943. this._options = options;
  56944. if (!this._isMainTrack) {
  56945. this._scene.soundTracks.push(this);
  56946. this.id = this._scene.soundTracks.length - 1;
  56947. }
  56948. }
  56949. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  56950. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56951. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  56952. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  56953. if (this._options) {
  56954. if (this._options.volume) {
  56955. this._outputAudioNode.gain.value = this._options.volume;
  56956. }
  56957. if (this._options.mainTrack) {
  56958. this._isMainTrack = this._options.mainTrack;
  56959. }
  56960. }
  56961. this._isInitialized = true;
  56962. }
  56963. };
  56964. SoundTrack.prototype.dispose = function () {
  56965. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  56966. if (this._connectedAnalyser) {
  56967. this._connectedAnalyser.stopDebugCanvas();
  56968. }
  56969. while (this.soundCollection.length) {
  56970. this.soundCollection[0].dispose();
  56971. }
  56972. if (this._outputAudioNode) {
  56973. this._outputAudioNode.disconnect();
  56974. }
  56975. this._outputAudioNode = null;
  56976. }
  56977. };
  56978. SoundTrack.prototype.AddSound = function (sound) {
  56979. if (!this._isInitialized) {
  56980. this._initializeSoundTrackAudioGraph();
  56981. }
  56982. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56983. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  56984. }
  56985. if (sound.soundTrackId) {
  56986. if (sound.soundTrackId === -1) {
  56987. this._scene.mainSoundTrack.RemoveSound(sound);
  56988. }
  56989. else {
  56990. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  56991. }
  56992. }
  56993. this.soundCollection.push(sound);
  56994. sound.soundTrackId = this.id;
  56995. };
  56996. SoundTrack.prototype.RemoveSound = function (sound) {
  56997. var index = this.soundCollection.indexOf(sound);
  56998. if (index !== -1) {
  56999. this.soundCollection.splice(index, 1);
  57000. }
  57001. };
  57002. SoundTrack.prototype.setVolume = function (newVolume) {
  57003. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57004. this._outputAudioNode.gain.value = newVolume;
  57005. }
  57006. };
  57007. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57008. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57009. for (var i = 0; i < this.soundCollection.length; i++) {
  57010. this.soundCollection[i].switchPanningModelToHRTF();
  57011. }
  57012. }
  57013. };
  57014. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57015. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57016. for (var i = 0; i < this.soundCollection.length; i++) {
  57017. this.soundCollection[i].switchPanningModelToEqualPower();
  57018. }
  57019. }
  57020. };
  57021. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57022. if (this._connectedAnalyser) {
  57023. this._connectedAnalyser.stopDebugCanvas();
  57024. }
  57025. this._connectedAnalyser = analyser;
  57026. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57027. this._outputAudioNode.disconnect();
  57028. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57029. }
  57030. };
  57031. return SoundTrack;
  57032. }());
  57033. BABYLON.SoundTrack = SoundTrack;
  57034. })(BABYLON || (BABYLON = {}));
  57035. //# sourceMappingURL=babylon.soundtrack.js.map
  57036. var BABYLON;
  57037. (function (BABYLON) {
  57038. var Analyser = /** @class */ (function () {
  57039. function Analyser(scene) {
  57040. this.SMOOTHING = 0.75;
  57041. this.FFT_SIZE = 512;
  57042. this.BARGRAPHAMPLITUDE = 256;
  57043. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57044. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57045. this._scene = scene;
  57046. this._audioEngine = BABYLON.Engine.audioEngine;
  57047. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57048. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57049. this._webAudioAnalyser.minDecibels = -140;
  57050. this._webAudioAnalyser.maxDecibels = 0;
  57051. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57052. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57053. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57054. }
  57055. }
  57056. Analyser.prototype.getFrequencyBinCount = function () {
  57057. if (this._audioEngine.canUseWebAudio) {
  57058. return this._webAudioAnalyser.frequencyBinCount;
  57059. }
  57060. else {
  57061. return 0;
  57062. }
  57063. };
  57064. Analyser.prototype.getByteFrequencyData = function () {
  57065. if (this._audioEngine.canUseWebAudio) {
  57066. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57067. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57068. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57069. }
  57070. return this._byteFreqs;
  57071. };
  57072. Analyser.prototype.getByteTimeDomainData = function () {
  57073. if (this._audioEngine.canUseWebAudio) {
  57074. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57075. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57076. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57077. }
  57078. return this._byteTime;
  57079. };
  57080. Analyser.prototype.getFloatFrequencyData = function () {
  57081. if (this._audioEngine.canUseWebAudio) {
  57082. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57083. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57084. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57085. }
  57086. return this._floatFreqs;
  57087. };
  57088. Analyser.prototype.drawDebugCanvas = function () {
  57089. var _this = this;
  57090. if (this._audioEngine.canUseWebAudio) {
  57091. if (!this._debugCanvas) {
  57092. this._debugCanvas = document.createElement("canvas");
  57093. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57094. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57095. this._debugCanvas.style.position = "absolute";
  57096. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57097. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57098. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57099. document.body.appendChild(this._debugCanvas);
  57100. this._registerFunc = function () {
  57101. _this.drawDebugCanvas();
  57102. };
  57103. this._scene.registerBeforeRender(this._registerFunc);
  57104. }
  57105. if (this._registerFunc && this._debugCanvasContext) {
  57106. var workingArray = this.getByteFrequencyData();
  57107. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57108. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57109. // Draw the frequency domain chart.
  57110. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57111. var value = workingArray[i];
  57112. var percent = value / this.BARGRAPHAMPLITUDE;
  57113. var height = this.DEBUGCANVASSIZE.height * percent;
  57114. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57115. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57116. var hue = i / this.getFrequencyBinCount() * 360;
  57117. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57118. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57119. }
  57120. }
  57121. }
  57122. };
  57123. Analyser.prototype.stopDebugCanvas = function () {
  57124. if (this._debugCanvas) {
  57125. if (this._registerFunc) {
  57126. this._scene.unregisterBeforeRender(this._registerFunc);
  57127. this._registerFunc = null;
  57128. }
  57129. document.body.removeChild(this._debugCanvas);
  57130. this._debugCanvas = null;
  57131. this._debugCanvasContext = null;
  57132. }
  57133. };
  57134. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57135. if (this._audioEngine.canUseWebAudio) {
  57136. inputAudioNode.connect(this._webAudioAnalyser);
  57137. this._webAudioAnalyser.connect(outputAudioNode);
  57138. }
  57139. };
  57140. Analyser.prototype.dispose = function () {
  57141. if (this._audioEngine.canUseWebAudio) {
  57142. this._webAudioAnalyser.disconnect();
  57143. }
  57144. };
  57145. return Analyser;
  57146. }());
  57147. BABYLON.Analyser = Analyser;
  57148. })(BABYLON || (BABYLON = {}));
  57149. //# sourceMappingURL=babylon.analyser.js.map
  57150. var BABYLON;
  57151. (function (BABYLON) {
  57152. var CubeTexture = /** @class */ (function (_super) {
  57153. __extends(CubeTexture, _super);
  57154. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57155. if (extensions === void 0) { extensions = null; }
  57156. if (noMipmap === void 0) { noMipmap = false; }
  57157. if (files === void 0) { files = null; }
  57158. if (onLoad === void 0) { onLoad = null; }
  57159. if (onError === void 0) { onError = null; }
  57160. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57161. if (prefiltered === void 0) { prefiltered = false; }
  57162. if (forcedExtension === void 0) { forcedExtension = null; }
  57163. var _this = _super.call(this, scene) || this;
  57164. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57165. /**
  57166. * Gets or sets the center of the bounding box associated with the cube texture
  57167. * It must define where the camera used to render the texture was set
  57168. */
  57169. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57170. _this.name = rootUrl;
  57171. _this.url = rootUrl;
  57172. _this._noMipmap = noMipmap;
  57173. _this.hasAlpha = false;
  57174. _this._format = format;
  57175. _this._prefiltered = prefiltered;
  57176. _this.isCube = true;
  57177. _this._textureMatrix = BABYLON.Matrix.Identity();
  57178. if (prefiltered) {
  57179. _this.gammaSpace = false;
  57180. }
  57181. if (!rootUrl && !files) {
  57182. return _this;
  57183. }
  57184. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57185. var lastDot = rootUrl.lastIndexOf(".");
  57186. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57187. var isDDS = (extension === ".dds");
  57188. if (!files) {
  57189. if (!isDDS && !extensions) {
  57190. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57191. }
  57192. files = [];
  57193. if (extensions) {
  57194. for (var index = 0; index < extensions.length; index++) {
  57195. files.push(rootUrl + extensions[index]);
  57196. }
  57197. }
  57198. }
  57199. _this._files = files;
  57200. if (!_this._texture) {
  57201. if (!scene.useDelayedTextureLoading) {
  57202. if (prefiltered) {
  57203. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57204. }
  57205. else {
  57206. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57207. }
  57208. }
  57209. else {
  57210. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57211. }
  57212. }
  57213. else if (onLoad) {
  57214. if (_this._texture.isReady) {
  57215. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57216. }
  57217. else {
  57218. _this._texture.onLoadedObservable.add(onLoad);
  57219. }
  57220. }
  57221. return _this;
  57222. }
  57223. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  57224. get: function () {
  57225. return this._boundingBoxSize;
  57226. },
  57227. /**
  57228. * Gets or sets the size of the bounding box associated with the cube texture
  57229. * When defined, the cubemap will switch to local mode
  57230. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57231. * @example https://www.babylonjs-playground.com/#RNASML
  57232. */
  57233. set: function (value) {
  57234. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57235. return;
  57236. }
  57237. this._boundingBoxSize = value;
  57238. var scene = this.getScene();
  57239. if (scene) {
  57240. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57241. }
  57242. },
  57243. enumerable: true,
  57244. configurable: true
  57245. });
  57246. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  57247. var rootUrlKey = "";
  57248. files.forEach(function (url) { return rootUrlKey += url; });
  57249. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  57250. };
  57251. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  57252. if (forcedExtension === void 0) { forcedExtension = null; }
  57253. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  57254. };
  57255. // Methods
  57256. CubeTexture.prototype.delayLoad = function () {
  57257. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57258. return;
  57259. }
  57260. var scene = this.getScene();
  57261. if (!scene) {
  57262. return;
  57263. }
  57264. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57265. this._texture = this._getFromCache(this.url, this._noMipmap);
  57266. if (!this._texture) {
  57267. if (this._prefiltered) {
  57268. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57269. }
  57270. else {
  57271. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57272. }
  57273. }
  57274. };
  57275. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57276. return this._textureMatrix;
  57277. };
  57278. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57279. this._textureMatrix = value;
  57280. };
  57281. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57282. var texture = BABYLON.SerializationHelper.Parse(function () {
  57283. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57284. }, parsedTexture, scene);
  57285. // Animations
  57286. if (parsedTexture.animations) {
  57287. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57288. var parsedAnimation = parsedTexture.animations[animationIndex];
  57289. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57290. }
  57291. }
  57292. return texture;
  57293. };
  57294. CubeTexture.prototype.clone = function () {
  57295. var _this = this;
  57296. return BABYLON.SerializationHelper.Clone(function () {
  57297. var scene = _this.getScene();
  57298. if (!scene) {
  57299. return _this;
  57300. }
  57301. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57302. }, this);
  57303. };
  57304. return CubeTexture;
  57305. }(BABYLON.BaseTexture));
  57306. BABYLON.CubeTexture = CubeTexture;
  57307. })(BABYLON || (BABYLON = {}));
  57308. //# sourceMappingURL=babylon.cubeTexture.js.map
  57309. var BABYLON;
  57310. (function (BABYLON) {
  57311. var RenderTargetTexture = /** @class */ (function (_super) {
  57312. __extends(RenderTargetTexture, _super);
  57313. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57314. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57315. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57316. if (isCube === void 0) { isCube = false; }
  57317. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57318. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57319. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  57320. if (isMulti === void 0) { isMulti = false; }
  57321. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57322. _this.isCube = isCube;
  57323. /**
  57324. * Use this list to define the list of mesh you want to render.
  57325. */
  57326. _this.renderList = new Array();
  57327. _this.renderParticles = true;
  57328. _this.renderSprites = false;
  57329. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  57330. _this.ignoreCameraViewport = false;
  57331. // Events
  57332. /**
  57333. * An event triggered when the texture is unbind.
  57334. * @type {BABYLON.Observable}
  57335. */
  57336. _this.onBeforeBindObservable = new BABYLON.Observable();
  57337. /**
  57338. * An event triggered when the texture is unbind.
  57339. * @type {BABYLON.Observable}
  57340. */
  57341. _this.onAfterUnbindObservable = new BABYLON.Observable();
  57342. /**
  57343. * An event triggered before rendering the texture
  57344. * @type {BABYLON.Observable}
  57345. */
  57346. _this.onBeforeRenderObservable = new BABYLON.Observable();
  57347. /**
  57348. * An event triggered after rendering the texture
  57349. * @type {BABYLON.Observable}
  57350. */
  57351. _this.onAfterRenderObservable = new BABYLON.Observable();
  57352. /**
  57353. * An event triggered after the texture clear
  57354. * @type {BABYLON.Observable}
  57355. */
  57356. _this.onClearObservable = new BABYLON.Observable();
  57357. _this._currentRefreshId = -1;
  57358. _this._refreshRate = 1;
  57359. _this._samples = 1;
  57360. /**
  57361. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  57362. * It must define where the camera used to render the texture is set
  57363. */
  57364. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57365. scene = _this.getScene();
  57366. if (!scene) {
  57367. return _this;
  57368. }
  57369. _this._engine = scene.getEngine();
  57370. _this.name = name;
  57371. _this.isRenderTarget = true;
  57372. _this._initialSizeParameter = size;
  57373. _this._processSizeParameter(size);
  57374. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  57375. });
  57376. _this._generateMipMaps = generateMipMaps ? true : false;
  57377. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  57378. // Rendering groups
  57379. _this._renderingManager = new BABYLON.RenderingManager(scene);
  57380. if (isMulti) {
  57381. return _this;
  57382. }
  57383. _this._renderTargetOptions = {
  57384. generateMipMaps: generateMipMaps,
  57385. type: type,
  57386. samplingMode: samplingMode,
  57387. generateDepthBuffer: generateDepthBuffer,
  57388. generateStencilBuffer: generateStencilBuffer
  57389. };
  57390. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  57391. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57392. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57393. }
  57394. if (isCube) {
  57395. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  57396. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  57397. _this._textureMatrix = BABYLON.Matrix.Identity();
  57398. }
  57399. else {
  57400. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  57401. }
  57402. return _this;
  57403. }
  57404. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  57405. get: function () {
  57406. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  57407. },
  57408. enumerable: true,
  57409. configurable: true
  57410. });
  57411. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  57412. get: function () {
  57413. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  57414. },
  57415. enumerable: true,
  57416. configurable: true
  57417. });
  57418. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  57419. get: function () {
  57420. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  57421. },
  57422. enumerable: true,
  57423. configurable: true
  57424. });
  57425. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  57426. set: function (callback) {
  57427. if (this._onAfterUnbindObserver) {
  57428. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  57429. }
  57430. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  57431. },
  57432. enumerable: true,
  57433. configurable: true
  57434. });
  57435. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  57436. set: function (callback) {
  57437. if (this._onBeforeRenderObserver) {
  57438. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57439. }
  57440. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57441. },
  57442. enumerable: true,
  57443. configurable: true
  57444. });
  57445. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  57446. set: function (callback) {
  57447. if (this._onAfterRenderObserver) {
  57448. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57449. }
  57450. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57451. },
  57452. enumerable: true,
  57453. configurable: true
  57454. });
  57455. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  57456. set: function (callback) {
  57457. if (this._onClearObserver) {
  57458. this.onClearObservable.remove(this._onClearObserver);
  57459. }
  57460. this._onClearObserver = this.onClearObservable.add(callback);
  57461. },
  57462. enumerable: true,
  57463. configurable: true
  57464. });
  57465. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  57466. get: function () {
  57467. return this._renderTargetOptions;
  57468. },
  57469. enumerable: true,
  57470. configurable: true
  57471. });
  57472. RenderTargetTexture.prototype._onRatioRescale = function () {
  57473. if (this._sizeRatio) {
  57474. this.resize(this._initialSizeParameter);
  57475. }
  57476. };
  57477. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  57478. get: function () {
  57479. return this._boundingBoxSize;
  57480. },
  57481. /**
  57482. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  57483. * When defined, the cubemap will switch to local mode
  57484. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57485. * @example https://www.babylonjs-playground.com/#RNASML
  57486. */
  57487. set: function (value) {
  57488. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57489. return;
  57490. }
  57491. this._boundingBoxSize = value;
  57492. var scene = this.getScene();
  57493. if (scene) {
  57494. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57495. }
  57496. },
  57497. enumerable: true,
  57498. configurable: true
  57499. });
  57500. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  57501. if (size.ratio) {
  57502. this._sizeRatio = size.ratio;
  57503. this._size = {
  57504. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  57505. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  57506. };
  57507. }
  57508. else {
  57509. this._size = size;
  57510. }
  57511. };
  57512. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  57513. get: function () {
  57514. return this._samples;
  57515. },
  57516. set: function (value) {
  57517. if (this._samples === value) {
  57518. return;
  57519. }
  57520. var scene = this.getScene();
  57521. if (!scene) {
  57522. return;
  57523. }
  57524. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  57525. },
  57526. enumerable: true,
  57527. configurable: true
  57528. });
  57529. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  57530. this._currentRefreshId = -1;
  57531. };
  57532. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  57533. get: function () {
  57534. return this._refreshRate;
  57535. },
  57536. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57537. set: function (value) {
  57538. this._refreshRate = value;
  57539. this.resetRefreshCounter();
  57540. },
  57541. enumerable: true,
  57542. configurable: true
  57543. });
  57544. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  57545. if (!this._postProcessManager) {
  57546. var scene = this.getScene();
  57547. if (!scene) {
  57548. return;
  57549. }
  57550. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  57551. this._postProcesses = new Array();
  57552. }
  57553. this._postProcesses.push(postProcess);
  57554. this._postProcesses[0].autoClear = false;
  57555. };
  57556. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  57557. if (!this._postProcesses) {
  57558. return;
  57559. }
  57560. if (dispose) {
  57561. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  57562. var postProcess = _a[_i];
  57563. postProcess.dispose();
  57564. }
  57565. }
  57566. this._postProcesses = [];
  57567. };
  57568. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  57569. if (!this._postProcesses) {
  57570. return;
  57571. }
  57572. var index = this._postProcesses.indexOf(postProcess);
  57573. if (index === -1) {
  57574. return;
  57575. }
  57576. this._postProcesses.splice(index, 1);
  57577. if (this._postProcesses.length > 0) {
  57578. this._postProcesses[0].autoClear = false;
  57579. }
  57580. };
  57581. RenderTargetTexture.prototype._shouldRender = function () {
  57582. if (this._currentRefreshId === -1) {
  57583. this._currentRefreshId = 1;
  57584. return true;
  57585. }
  57586. if (this.refreshRate === this._currentRefreshId) {
  57587. this._currentRefreshId = 1;
  57588. return true;
  57589. }
  57590. this._currentRefreshId++;
  57591. return false;
  57592. };
  57593. RenderTargetTexture.prototype.getRenderSize = function () {
  57594. if (this._size.width) {
  57595. return this._size.width;
  57596. }
  57597. return this._size;
  57598. };
  57599. RenderTargetTexture.prototype.getRenderWidth = function () {
  57600. if (this._size.width) {
  57601. return this._size.width;
  57602. }
  57603. return this._size;
  57604. };
  57605. RenderTargetTexture.prototype.getRenderHeight = function () {
  57606. if (this._size.width) {
  57607. return this._size.height;
  57608. }
  57609. return this._size;
  57610. };
  57611. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  57612. get: function () {
  57613. return true;
  57614. },
  57615. enumerable: true,
  57616. configurable: true
  57617. });
  57618. RenderTargetTexture.prototype.scale = function (ratio) {
  57619. var newSize = this.getRenderSize() * ratio;
  57620. this.resize(newSize);
  57621. };
  57622. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  57623. if (this.isCube) {
  57624. return this._textureMatrix;
  57625. }
  57626. return _super.prototype.getReflectionTextureMatrix.call(this);
  57627. };
  57628. RenderTargetTexture.prototype.resize = function (size) {
  57629. this.releaseInternalTexture();
  57630. var scene = this.getScene();
  57631. if (!scene) {
  57632. return;
  57633. }
  57634. this._processSizeParameter(size);
  57635. if (this.isCube) {
  57636. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  57637. }
  57638. else {
  57639. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  57640. }
  57641. };
  57642. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  57643. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  57644. if (dumpForDebug === void 0) { dumpForDebug = false; }
  57645. var scene = this.getScene();
  57646. if (!scene) {
  57647. return;
  57648. }
  57649. var engine = scene.getEngine();
  57650. if (this.useCameraPostProcesses !== undefined) {
  57651. useCameraPostProcess = this.useCameraPostProcesses;
  57652. }
  57653. if (this._waitingRenderList) {
  57654. this.renderList = [];
  57655. for (var index = 0; index < this._waitingRenderList.length; index++) {
  57656. var id = this._waitingRenderList[index];
  57657. var mesh_1 = scene.getMeshByID(id);
  57658. if (mesh_1) {
  57659. this.renderList.push(mesh_1);
  57660. }
  57661. }
  57662. delete this._waitingRenderList;
  57663. }
  57664. // Is predicate defined?
  57665. if (this.renderListPredicate) {
  57666. if (this.renderList) {
  57667. this.renderList.splice(0); // Clear previous renderList
  57668. }
  57669. else {
  57670. this.renderList = [];
  57671. }
  57672. var scene = this.getScene();
  57673. if (!scene) {
  57674. return;
  57675. }
  57676. var sceneMeshes = scene.meshes;
  57677. for (var index = 0; index < sceneMeshes.length; index++) {
  57678. var mesh = sceneMeshes[index];
  57679. if (this.renderListPredicate(mesh)) {
  57680. this.renderList.push(mesh);
  57681. }
  57682. }
  57683. }
  57684. this.onBeforeBindObservable.notifyObservers(this);
  57685. // Set custom projection.
  57686. // Needs to be before binding to prevent changing the aspect ratio.
  57687. var camera;
  57688. if (this.activeCamera) {
  57689. camera = this.activeCamera;
  57690. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57691. if (this.activeCamera !== scene.activeCamera) {
  57692. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  57693. }
  57694. }
  57695. else {
  57696. camera = scene.activeCamera;
  57697. if (camera) {
  57698. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57699. }
  57700. }
  57701. // Prepare renderingManager
  57702. this._renderingManager.reset();
  57703. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  57704. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  57705. var sceneRenderId = scene.getRenderId();
  57706. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  57707. var mesh = currentRenderList[meshIndex];
  57708. if (mesh) {
  57709. if (!mesh.isReady()) {
  57710. // Reset _currentRefreshId
  57711. this.resetRefreshCounter();
  57712. continue;
  57713. }
  57714. mesh._preActivateForIntermediateRendering(sceneRenderId);
  57715. var isMasked = void 0;
  57716. if (!this.renderList && camera) {
  57717. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  57718. }
  57719. else {
  57720. isMasked = false;
  57721. }
  57722. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  57723. mesh._activate(sceneRenderId);
  57724. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  57725. var subMesh = mesh.subMeshes[subIndex];
  57726. scene._activeIndices.addCount(subMesh.indexCount, false);
  57727. this._renderingManager.dispatch(subMesh, mesh);
  57728. }
  57729. }
  57730. }
  57731. }
  57732. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  57733. var particleSystem = scene.particleSystems[particleIndex];
  57734. var emitter = particleSystem.emitter;
  57735. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  57736. continue;
  57737. }
  57738. if (currentRenderList.indexOf(emitter) >= 0) {
  57739. this._renderingManager.dispatchParticles(particleSystem);
  57740. }
  57741. }
  57742. if (this.isCube) {
  57743. for (var face = 0; face < 6; face++) {
  57744. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57745. scene.incrementRenderId();
  57746. scene.resetCachedMaterial();
  57747. }
  57748. }
  57749. else {
  57750. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57751. }
  57752. this.onAfterUnbindObservable.notifyObservers(this);
  57753. if (scene.activeCamera) {
  57754. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  57755. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  57756. }
  57757. engine.setViewport(scene.activeCamera.viewport);
  57758. }
  57759. scene.resetCachedMaterial();
  57760. };
  57761. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  57762. var minimum = 128;
  57763. var x = renderDimension * scale;
  57764. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  57765. // Ensure we don't exceed the render dimension (while staying POT)
  57766. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  57767. };
  57768. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57769. var _this = this;
  57770. if (!this._texture) {
  57771. return;
  57772. }
  57773. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  57774. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57775. });
  57776. };
  57777. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  57778. var scene = this.getScene();
  57779. if (!scene) {
  57780. return;
  57781. }
  57782. var engine = scene.getEngine();
  57783. if (!this._texture) {
  57784. return;
  57785. }
  57786. // Bind
  57787. if (this._postProcessManager) {
  57788. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  57789. }
  57790. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  57791. if (this._texture) {
  57792. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  57793. }
  57794. }
  57795. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  57796. // Clear
  57797. if (this.onClearObservable.hasObservers()) {
  57798. this.onClearObservable.notifyObservers(engine);
  57799. }
  57800. else {
  57801. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  57802. }
  57803. if (!this._doNotChangeAspectRatio) {
  57804. scene.updateTransformMatrix(true);
  57805. }
  57806. // Render
  57807. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  57808. if (this._postProcessManager) {
  57809. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  57810. }
  57811. else if (useCameraPostProcess) {
  57812. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  57813. }
  57814. if (!this._doNotChangeAspectRatio) {
  57815. scene.updateTransformMatrix(true);
  57816. }
  57817. // Dump ?
  57818. if (dumpForDebug) {
  57819. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  57820. }
  57821. // Unbind
  57822. if (!this.isCube || faceIndex === 5) {
  57823. if (this.isCube) {
  57824. if (faceIndex === 5) {
  57825. engine.generateMipMapsForCubemap(this._texture);
  57826. }
  57827. }
  57828. this.unbindFrameBuffer(engine, faceIndex);
  57829. }
  57830. else {
  57831. this.onAfterRenderObservable.notifyObservers(faceIndex);
  57832. }
  57833. };
  57834. /**
  57835. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  57836. * This allowed control for front to back rendering or reversly depending of the special needs.
  57837. *
  57838. * @param renderingGroupId The rendering group id corresponding to its index
  57839. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  57840. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  57841. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  57842. */
  57843. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  57844. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  57845. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  57846. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  57847. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  57848. };
  57849. /**
  57850. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  57851. *
  57852. * @param renderingGroupId The rendering group id corresponding to its index
  57853. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  57854. */
  57855. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  57856. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  57857. };
  57858. RenderTargetTexture.prototype.clone = function () {
  57859. var textureSize = this.getSize();
  57860. 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);
  57861. // Base texture
  57862. newTexture.hasAlpha = this.hasAlpha;
  57863. newTexture.level = this.level;
  57864. // RenderTarget Texture
  57865. newTexture.coordinatesMode = this.coordinatesMode;
  57866. if (this.renderList) {
  57867. newTexture.renderList = this.renderList.slice(0);
  57868. }
  57869. return newTexture;
  57870. };
  57871. RenderTargetTexture.prototype.serialize = function () {
  57872. if (!this.name) {
  57873. return null;
  57874. }
  57875. var serializationObject = _super.prototype.serialize.call(this);
  57876. serializationObject.renderTargetSize = this.getRenderSize();
  57877. serializationObject.renderList = [];
  57878. if (this.renderList) {
  57879. for (var index = 0; index < this.renderList.length; index++) {
  57880. serializationObject.renderList.push(this.renderList[index].id);
  57881. }
  57882. }
  57883. return serializationObject;
  57884. };
  57885. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  57886. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  57887. var objBuffer = this.getInternalTexture();
  57888. var scene = this.getScene();
  57889. if (objBuffer && scene) {
  57890. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  57891. }
  57892. };
  57893. RenderTargetTexture.prototype.dispose = function () {
  57894. if (this._postProcessManager) {
  57895. this._postProcessManager.dispose();
  57896. this._postProcessManager = null;
  57897. }
  57898. this.clearPostProcesses(true);
  57899. if (this._resizeObserver) {
  57900. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  57901. this._resizeObserver = null;
  57902. }
  57903. this.renderList = null;
  57904. // Remove from custom render targets
  57905. var scene = this.getScene();
  57906. if (!scene) {
  57907. return;
  57908. }
  57909. var index = scene.customRenderTargets.indexOf(this);
  57910. if (index >= 0) {
  57911. scene.customRenderTargets.splice(index, 1);
  57912. }
  57913. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  57914. var camera = _a[_i];
  57915. index = camera.customRenderTargets.indexOf(this);
  57916. if (index >= 0) {
  57917. camera.customRenderTargets.splice(index, 1);
  57918. }
  57919. }
  57920. _super.prototype.dispose.call(this);
  57921. };
  57922. RenderTargetTexture.prototype._rebuild = function () {
  57923. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57924. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57925. }
  57926. if (this._postProcessManager) {
  57927. this._postProcessManager._rebuild();
  57928. }
  57929. };
  57930. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  57931. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  57932. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  57933. return RenderTargetTexture;
  57934. }(BABYLON.Texture));
  57935. BABYLON.RenderTargetTexture = RenderTargetTexture;
  57936. })(BABYLON || (BABYLON = {}));
  57937. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  57938. var BABYLON;
  57939. (function (BABYLON) {
  57940. ;
  57941. var MultiRenderTarget = /** @class */ (function (_super) {
  57942. __extends(MultiRenderTarget, _super);
  57943. function MultiRenderTarget(name, size, count, scene, options) {
  57944. var _this = this;
  57945. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  57946. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  57947. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  57948. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  57949. _this._engine = scene.getEngine();
  57950. if (!_this.isSupported) {
  57951. _this.dispose();
  57952. return;
  57953. }
  57954. var types = [];
  57955. var samplingModes = [];
  57956. for (var i = 0; i < count; i++) {
  57957. if (options && options.types && options.types[i] !== undefined) {
  57958. types.push(options.types[i]);
  57959. }
  57960. else {
  57961. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57962. }
  57963. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  57964. samplingModes.push(options.samplingModes[i]);
  57965. }
  57966. else {
  57967. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57968. }
  57969. }
  57970. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  57971. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  57972. _this._size = size;
  57973. _this._multiRenderTargetOptions = {
  57974. samplingModes: samplingModes,
  57975. generateMipMaps: generateMipMaps,
  57976. generateDepthBuffer: generateDepthBuffer,
  57977. generateStencilBuffer: generateStencilBuffer,
  57978. generateDepthTexture: generateDepthTexture,
  57979. types: types,
  57980. textureCount: count
  57981. };
  57982. _this._createInternalTextures();
  57983. _this._createTextures();
  57984. return _this;
  57985. }
  57986. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  57987. get: function () {
  57988. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  57989. },
  57990. enumerable: true,
  57991. configurable: true
  57992. });
  57993. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  57994. get: function () {
  57995. return this._textures;
  57996. },
  57997. enumerable: true,
  57998. configurable: true
  57999. });
  58000. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58001. get: function () {
  58002. return this._textures[this._textures.length - 1];
  58003. },
  58004. enumerable: true,
  58005. configurable: true
  58006. });
  58007. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58008. set: function (wrap) {
  58009. if (this._textures) {
  58010. for (var i = 0; i < this._textures.length; i++) {
  58011. this._textures[i].wrapU = wrap;
  58012. }
  58013. }
  58014. },
  58015. enumerable: true,
  58016. configurable: true
  58017. });
  58018. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58019. set: function (wrap) {
  58020. if (this._textures) {
  58021. for (var i = 0; i < this._textures.length; i++) {
  58022. this._textures[i].wrapV = wrap;
  58023. }
  58024. }
  58025. },
  58026. enumerable: true,
  58027. configurable: true
  58028. });
  58029. MultiRenderTarget.prototype._rebuild = function () {
  58030. this.releaseInternalTextures();
  58031. this._createInternalTextures();
  58032. for (var i = 0; i < this._internalTextures.length; i++) {
  58033. var texture = this._textures[i];
  58034. texture._texture = this._internalTextures[i];
  58035. }
  58036. // Keeps references to frame buffer and stencil/depth buffer
  58037. this._texture = this._internalTextures[0];
  58038. };
  58039. MultiRenderTarget.prototype._createInternalTextures = function () {
  58040. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58041. };
  58042. MultiRenderTarget.prototype._createTextures = function () {
  58043. this._textures = [];
  58044. for (var i = 0; i < this._internalTextures.length; i++) {
  58045. var texture = new BABYLON.Texture(null, this.getScene());
  58046. texture._texture = this._internalTextures[i];
  58047. this._textures.push(texture);
  58048. }
  58049. // Keeps references to frame buffer and stencil/depth buffer
  58050. this._texture = this._internalTextures[0];
  58051. };
  58052. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58053. get: function () {
  58054. return this._samples;
  58055. },
  58056. set: function (value) {
  58057. if (this._samples === value) {
  58058. return;
  58059. }
  58060. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58061. },
  58062. enumerable: true,
  58063. configurable: true
  58064. });
  58065. MultiRenderTarget.prototype.resize = function (size) {
  58066. this.releaseInternalTextures();
  58067. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58068. this._createInternalTextures();
  58069. };
  58070. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58071. var _this = this;
  58072. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58073. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58074. });
  58075. };
  58076. MultiRenderTarget.prototype.dispose = function () {
  58077. this.releaseInternalTextures();
  58078. _super.prototype.dispose.call(this);
  58079. };
  58080. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58081. if (!this._internalTextures) {
  58082. return;
  58083. }
  58084. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58085. if (this._internalTextures[i] !== undefined) {
  58086. this._internalTextures[i].dispose();
  58087. this._internalTextures.splice(i, 1);
  58088. }
  58089. }
  58090. };
  58091. return MultiRenderTarget;
  58092. }(BABYLON.RenderTargetTexture));
  58093. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58094. })(BABYLON || (BABYLON = {}));
  58095. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58096. var BABYLON;
  58097. (function (BABYLON) {
  58098. var MirrorTexture = /** @class */ (function (_super) {
  58099. __extends(MirrorTexture, _super);
  58100. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58101. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58102. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58103. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58104. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58105. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58106. _this._transformMatrix = BABYLON.Matrix.Zero();
  58107. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58108. _this._adaptiveBlurKernel = 0;
  58109. _this._blurKernelX = 0;
  58110. _this._blurKernelY = 0;
  58111. _this._blurRatio = 1.0;
  58112. _this.ignoreCameraViewport = true;
  58113. _this.onBeforeRenderObservable.add(function () {
  58114. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58115. _this._savedViewMatrix = scene.getViewMatrix();
  58116. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58117. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58118. scene.clipPlane = _this.mirrorPlane;
  58119. scene.getEngine().cullBackFaces = false;
  58120. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58121. });
  58122. _this.onAfterRenderObservable.add(function () {
  58123. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58124. scene.getEngine().cullBackFaces = true;
  58125. scene._mirroredCameraPosition = null;
  58126. delete scene.clipPlane;
  58127. });
  58128. return _this;
  58129. }
  58130. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58131. get: function () {
  58132. return this._blurRatio;
  58133. },
  58134. set: function (value) {
  58135. if (this._blurRatio === value) {
  58136. return;
  58137. }
  58138. this._blurRatio = value;
  58139. this._preparePostProcesses();
  58140. },
  58141. enumerable: true,
  58142. configurable: true
  58143. });
  58144. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58145. set: function (value) {
  58146. this._adaptiveBlurKernel = value;
  58147. this._autoComputeBlurKernel();
  58148. },
  58149. enumerable: true,
  58150. configurable: true
  58151. });
  58152. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58153. set: function (value) {
  58154. this.blurKernelX = value;
  58155. this.blurKernelY = value;
  58156. },
  58157. enumerable: true,
  58158. configurable: true
  58159. });
  58160. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58161. get: function () {
  58162. return this._blurKernelX;
  58163. },
  58164. set: function (value) {
  58165. if (this._blurKernelX === value) {
  58166. return;
  58167. }
  58168. this._blurKernelX = value;
  58169. this._preparePostProcesses();
  58170. },
  58171. enumerable: true,
  58172. configurable: true
  58173. });
  58174. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  58175. get: function () {
  58176. return this._blurKernelY;
  58177. },
  58178. set: function (value) {
  58179. if (this._blurKernelY === value) {
  58180. return;
  58181. }
  58182. this._blurKernelY = value;
  58183. this._preparePostProcesses();
  58184. },
  58185. enumerable: true,
  58186. configurable: true
  58187. });
  58188. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  58189. var engine = this.getScene().getEngine();
  58190. var dw = this.getRenderWidth() / engine.getRenderWidth();
  58191. var dh = this.getRenderHeight() / engine.getRenderHeight();
  58192. this.blurKernelX = this._adaptiveBlurKernel * dw;
  58193. this.blurKernelY = this._adaptiveBlurKernel * dh;
  58194. };
  58195. MirrorTexture.prototype._onRatioRescale = function () {
  58196. if (this._sizeRatio) {
  58197. this.resize(this._initialSizeParameter);
  58198. if (!this._adaptiveBlurKernel) {
  58199. this._preparePostProcesses();
  58200. }
  58201. }
  58202. if (this._adaptiveBlurKernel) {
  58203. this._autoComputeBlurKernel();
  58204. }
  58205. };
  58206. MirrorTexture.prototype._preparePostProcesses = function () {
  58207. this.clearPostProcesses(true);
  58208. if (this._blurKernelX && this._blurKernelY) {
  58209. var engine = this.getScene().getEngine();
  58210. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58211. 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);
  58212. this._blurX.autoClear = false;
  58213. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  58214. this._blurX.inputTexture = this._texture;
  58215. }
  58216. else {
  58217. this._blurX.alwaysForcePOT = true;
  58218. }
  58219. 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);
  58220. this._blurY.autoClear = false;
  58221. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  58222. this.addPostProcess(this._blurX);
  58223. this.addPostProcess(this._blurY);
  58224. }
  58225. else {
  58226. if (this._blurY) {
  58227. this.removePostProcess(this._blurY);
  58228. this._blurY.dispose();
  58229. this._blurY = null;
  58230. }
  58231. if (this._blurX) {
  58232. this.removePostProcess(this._blurX);
  58233. this._blurX.dispose();
  58234. this._blurX = null;
  58235. }
  58236. }
  58237. };
  58238. MirrorTexture.prototype.clone = function () {
  58239. var scene = this.getScene();
  58240. if (!scene) {
  58241. return this;
  58242. }
  58243. var textureSize = this.getSize();
  58244. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58245. // Base texture
  58246. newTexture.hasAlpha = this.hasAlpha;
  58247. newTexture.level = this.level;
  58248. // Mirror Texture
  58249. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58250. if (this.renderList) {
  58251. newTexture.renderList = this.renderList.slice(0);
  58252. }
  58253. return newTexture;
  58254. };
  58255. MirrorTexture.prototype.serialize = function () {
  58256. if (!this.name) {
  58257. return null;
  58258. }
  58259. var serializationObject = _super.prototype.serialize.call(this);
  58260. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58261. return serializationObject;
  58262. };
  58263. return MirrorTexture;
  58264. }(BABYLON.RenderTargetTexture));
  58265. BABYLON.MirrorTexture = MirrorTexture;
  58266. })(BABYLON || (BABYLON = {}));
  58267. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58268. var BABYLON;
  58269. (function (BABYLON) {
  58270. /**
  58271. * Creates a refraction texture used by refraction channel of the standard material.
  58272. * @param name the texture name
  58273. * @param size size of the underlying texture
  58274. * @param scene root scene
  58275. */
  58276. var RefractionTexture = /** @class */ (function (_super) {
  58277. __extends(RefractionTexture, _super);
  58278. function RefractionTexture(name, size, scene, generateMipMaps) {
  58279. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58280. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58281. _this.depth = 2.0;
  58282. _this.onBeforeRenderObservable.add(function () {
  58283. scene.clipPlane = _this.refractionPlane;
  58284. });
  58285. _this.onAfterRenderObservable.add(function () {
  58286. delete scene.clipPlane;
  58287. });
  58288. return _this;
  58289. }
  58290. RefractionTexture.prototype.clone = function () {
  58291. var scene = this.getScene();
  58292. if (!scene) {
  58293. return this;
  58294. }
  58295. var textureSize = this.getSize();
  58296. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58297. // Base texture
  58298. newTexture.hasAlpha = this.hasAlpha;
  58299. newTexture.level = this.level;
  58300. // Refraction Texture
  58301. newTexture.refractionPlane = this.refractionPlane.clone();
  58302. if (this.renderList) {
  58303. newTexture.renderList = this.renderList.slice(0);
  58304. }
  58305. newTexture.depth = this.depth;
  58306. return newTexture;
  58307. };
  58308. RefractionTexture.prototype.serialize = function () {
  58309. if (!this.name) {
  58310. return null;
  58311. }
  58312. var serializationObject = _super.prototype.serialize.call(this);
  58313. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58314. serializationObject.depth = this.depth;
  58315. return serializationObject;
  58316. };
  58317. return RefractionTexture;
  58318. }(BABYLON.RenderTargetTexture));
  58319. BABYLON.RefractionTexture = RefractionTexture;
  58320. })(BABYLON || (BABYLON = {}));
  58321. //# sourceMappingURL=babylon.refractionTexture.js.map
  58322. var BABYLON;
  58323. (function (BABYLON) {
  58324. var DynamicTexture = /** @class */ (function (_super) {
  58325. __extends(DynamicTexture, _super);
  58326. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  58327. if (scene === void 0) { scene = null; }
  58328. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58329. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58330. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  58331. _this.name = name;
  58332. _this._engine = _this.getScene().getEngine();
  58333. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58334. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58335. _this._generateMipMaps = generateMipMaps;
  58336. if (options.getContext) {
  58337. _this._canvas = options;
  58338. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58339. }
  58340. else {
  58341. _this._canvas = document.createElement("canvas");
  58342. if (options.width) {
  58343. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58344. }
  58345. else {
  58346. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  58347. }
  58348. }
  58349. var textureSize = _this.getSize();
  58350. _this._canvas.width = textureSize.width;
  58351. _this._canvas.height = textureSize.height;
  58352. _this._context = _this._canvas.getContext("2d");
  58353. return _this;
  58354. }
  58355. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  58356. get: function () {
  58357. return true;
  58358. },
  58359. enumerable: true,
  58360. configurable: true
  58361. });
  58362. DynamicTexture.prototype._recreate = function (textureSize) {
  58363. this._canvas.width = textureSize.width;
  58364. this._canvas.height = textureSize.height;
  58365. this.releaseInternalTexture();
  58366. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  58367. };
  58368. DynamicTexture.prototype.scale = function (ratio) {
  58369. var textureSize = this.getSize();
  58370. textureSize.width *= ratio;
  58371. textureSize.height *= ratio;
  58372. this._recreate(textureSize);
  58373. };
  58374. DynamicTexture.prototype.scaleTo = function (width, height) {
  58375. var textureSize = this.getSize();
  58376. textureSize.width = width;
  58377. textureSize.height = height;
  58378. this._recreate(textureSize);
  58379. };
  58380. DynamicTexture.prototype.getContext = function () {
  58381. return this._context;
  58382. };
  58383. DynamicTexture.prototype.clear = function () {
  58384. var size = this.getSize();
  58385. this._context.fillRect(0, 0, size.width, size.height);
  58386. };
  58387. DynamicTexture.prototype.update = function (invertY) {
  58388. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  58389. };
  58390. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  58391. if (update === void 0) { update = true; }
  58392. var size = this.getSize();
  58393. if (clearColor) {
  58394. this._context.fillStyle = clearColor;
  58395. this._context.fillRect(0, 0, size.width, size.height);
  58396. }
  58397. this._context.font = font;
  58398. if (x === null || x === undefined) {
  58399. var textSize = this._context.measureText(text);
  58400. x = (size.width - textSize.width) / 2;
  58401. }
  58402. if (y === null || y === undefined) {
  58403. var fontSize = parseInt((font.replace(/\D/g, '')));
  58404. ;
  58405. y = (size.height / 2) + (fontSize / 3.65);
  58406. }
  58407. this._context.fillStyle = color;
  58408. this._context.fillText(text, x, y);
  58409. if (update) {
  58410. this.update(invertY);
  58411. }
  58412. };
  58413. DynamicTexture.prototype.clone = function () {
  58414. var scene = this.getScene();
  58415. if (!scene) {
  58416. return this;
  58417. }
  58418. var textureSize = this.getSize();
  58419. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  58420. // Base texture
  58421. newTexture.hasAlpha = this.hasAlpha;
  58422. newTexture.level = this.level;
  58423. // Dynamic Texture
  58424. newTexture.wrapU = this.wrapU;
  58425. newTexture.wrapV = this.wrapV;
  58426. return newTexture;
  58427. };
  58428. DynamicTexture.prototype._rebuild = function () {
  58429. this.update();
  58430. };
  58431. return DynamicTexture;
  58432. }(BABYLON.Texture));
  58433. BABYLON.DynamicTexture = DynamicTexture;
  58434. })(BABYLON || (BABYLON = {}));
  58435. //# sourceMappingURL=babylon.dynamicTexture.js.map
  58436. var BABYLON;
  58437. (function (BABYLON) {
  58438. var VideoTexture = /** @class */ (function (_super) {
  58439. __extends(VideoTexture, _super);
  58440. /**
  58441. * Creates a video texture.
  58442. * Sample : https://doc.babylonjs.com/how_to/video_texture
  58443. * @param {string | null} name optional name, will detect from video source, if not defined
  58444. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  58445. * @param {BABYLON.Scene} scene is obviously the current scene.
  58446. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  58447. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  58448. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  58449. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  58450. */
  58451. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  58452. if (generateMipMaps === void 0) { generateMipMaps = false; }
  58453. if (invertY === void 0) { invertY = false; }
  58454. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58455. if (settings === void 0) { settings = {
  58456. autoPlay: true,
  58457. loop: true,
  58458. autoUpdateTexture: true,
  58459. }; }
  58460. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58461. _this._createInternalTexture = function () {
  58462. if (_this._texture != null) {
  58463. return;
  58464. }
  58465. if (!_this._engine.needPOTTextures ||
  58466. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  58467. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58468. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58469. }
  58470. else {
  58471. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58472. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58473. _this._generateMipMaps = false;
  58474. }
  58475. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  58476. _this._texture.isReady = true;
  58477. _this._updateInternalTexture();
  58478. };
  58479. _this.reset = function () {
  58480. if (_this._texture == null) {
  58481. return;
  58482. }
  58483. _this._texture.dispose();
  58484. _this._texture = null;
  58485. };
  58486. _this._updateInternalTexture = function (e) {
  58487. if (_this._texture == null || !_this._texture.isReady) {
  58488. return;
  58489. }
  58490. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  58491. return;
  58492. }
  58493. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  58494. };
  58495. _this._engine = _this.getScene().getEngine();
  58496. _this._generateMipMaps = generateMipMaps;
  58497. _this._samplingMode = samplingMode;
  58498. _this.autoUpdateTexture = settings.autoUpdateTexture;
  58499. _this.name = name || _this._getName(src);
  58500. _this.video = _this._getVideo(src);
  58501. if (settings.autoPlay !== undefined) {
  58502. _this.video.autoplay = settings.autoPlay;
  58503. }
  58504. if (settings.loop !== undefined) {
  58505. _this.video.loop = settings.loop;
  58506. }
  58507. _this.video.addEventListener("canplay", _this._createInternalTexture);
  58508. _this.video.addEventListener("paused", _this._updateInternalTexture);
  58509. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  58510. _this.video.addEventListener("emptied", _this.reset);
  58511. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  58512. _this._createInternalTexture();
  58513. }
  58514. return _this;
  58515. }
  58516. VideoTexture.prototype._getName = function (src) {
  58517. if (src instanceof HTMLVideoElement) {
  58518. return src.currentSrc;
  58519. }
  58520. if (typeof src === "object") {
  58521. return src.toString();
  58522. }
  58523. return src;
  58524. };
  58525. ;
  58526. VideoTexture.prototype._getVideo = function (src) {
  58527. if (src instanceof HTMLVideoElement) {
  58528. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  58529. return src;
  58530. }
  58531. var video = document.createElement("video");
  58532. if (typeof src === "string") {
  58533. BABYLON.Tools.SetCorsBehavior(src, video);
  58534. video.src = src;
  58535. }
  58536. else {
  58537. BABYLON.Tools.SetCorsBehavior(src[0], video);
  58538. src.forEach(function (url) {
  58539. var source = document.createElement("source");
  58540. source.src = url;
  58541. video.appendChild(source);
  58542. });
  58543. }
  58544. return video;
  58545. };
  58546. ;
  58547. /**
  58548. * Internal method to initiate `update`.
  58549. */
  58550. VideoTexture.prototype._rebuild = function () {
  58551. this.update();
  58552. };
  58553. /**
  58554. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  58555. */
  58556. VideoTexture.prototype.update = function () {
  58557. if (!this.autoUpdateTexture) {
  58558. // Expecting user to call `updateTexture` manually
  58559. return;
  58560. }
  58561. this.updateTexture(true);
  58562. };
  58563. /**
  58564. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  58565. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  58566. */
  58567. VideoTexture.prototype.updateTexture = function (isVisible) {
  58568. if (!isVisible) {
  58569. return;
  58570. }
  58571. if (this.video.paused) {
  58572. return;
  58573. }
  58574. this._updateInternalTexture();
  58575. };
  58576. /**
  58577. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  58578. * @param url New url.
  58579. */
  58580. VideoTexture.prototype.updateURL = function (url) {
  58581. this.video.src = url;
  58582. };
  58583. VideoTexture.prototype.dispose = function () {
  58584. _super.prototype.dispose.call(this);
  58585. this.video.removeEventListener("canplay", this._createInternalTexture);
  58586. this.video.removeEventListener("paused", this._updateInternalTexture);
  58587. this.video.removeEventListener("seeked", this._updateInternalTexture);
  58588. this.video.removeEventListener("emptied", this.reset);
  58589. };
  58590. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  58591. var video = document.createElement("video");
  58592. var constraintsDeviceId;
  58593. if (constraints && constraints.deviceId) {
  58594. constraintsDeviceId = {
  58595. exact: constraints.deviceId,
  58596. };
  58597. }
  58598. navigator.getUserMedia =
  58599. navigator.getUserMedia ||
  58600. navigator.webkitGetUserMedia ||
  58601. navigator.mozGetUserMedia ||
  58602. navigator.msGetUserMedia;
  58603. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  58604. if (navigator.getUserMedia) {
  58605. navigator.getUserMedia({
  58606. video: {
  58607. deviceId: constraintsDeviceId,
  58608. width: {
  58609. min: (constraints && constraints.minWidth) || 256,
  58610. max: (constraints && constraints.maxWidth) || 640,
  58611. },
  58612. height: {
  58613. min: (constraints && constraints.minHeight) || 256,
  58614. max: (constraints && constraints.maxHeight) || 480,
  58615. },
  58616. },
  58617. }, function (stream) {
  58618. if (video.mozSrcObject !== undefined) {
  58619. // hack for Firefox < 19
  58620. video.mozSrcObject = stream;
  58621. }
  58622. else {
  58623. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  58624. }
  58625. video.play();
  58626. if (onReady) {
  58627. onReady(new VideoTexture("video", video, scene, true, true));
  58628. }
  58629. }, function (e) {
  58630. BABYLON.Tools.Error(e.name);
  58631. });
  58632. }
  58633. };
  58634. return VideoTexture;
  58635. }(BABYLON.Texture));
  58636. BABYLON.VideoTexture = VideoTexture;
  58637. })(BABYLON || (BABYLON = {}));
  58638. //# sourceMappingURL=babylon.videoTexture.js.map
  58639. var BABYLON;
  58640. (function (BABYLON) {
  58641. var RawTexture = /** @class */ (function (_super) {
  58642. __extends(RawTexture, _super);
  58643. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  58644. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58645. if (invertY === void 0) { invertY = false; }
  58646. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58647. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58648. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58649. _this.format = format;
  58650. _this._engine = scene.getEngine();
  58651. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  58652. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58653. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58654. return _this;
  58655. }
  58656. RawTexture.prototype.update = function (data) {
  58657. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  58658. };
  58659. // Statics
  58660. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58661. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58662. if (invertY === void 0) { invertY = false; }
  58663. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58664. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  58665. };
  58666. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58667. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58668. if (invertY === void 0) { invertY = false; }
  58669. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58670. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58671. };
  58672. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58673. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58674. if (invertY === void 0) { invertY = false; }
  58675. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58676. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58677. };
  58678. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58679. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58680. if (invertY === void 0) { invertY = false; }
  58681. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58682. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58683. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  58684. };
  58685. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58686. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58687. if (invertY === void 0) { invertY = false; }
  58688. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58689. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58690. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  58691. };
  58692. return RawTexture;
  58693. }(BABYLON.Texture));
  58694. BABYLON.RawTexture = RawTexture;
  58695. })(BABYLON || (BABYLON = {}));
  58696. //# sourceMappingURL=babylon.rawTexture.js.map
  58697. var BABYLON;
  58698. (function (BABYLON) {
  58699. /**
  58700. * PostProcess can be used to apply a shader to a texture after it has been rendered
  58701. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  58702. */
  58703. var PostProcess = /** @class */ (function () {
  58704. /**
  58705. * Creates a new instance of @see PostProcess
  58706. * @param name The name of the PostProcess.
  58707. * @param fragmentUrl The url of the fragment shader to be used.
  58708. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  58709. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  58710. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  58711. * @param camera The camera to apply the render pass to.
  58712. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  58713. * @param engine The engine which the post process will be applied. (default: current engine)
  58714. * @param reusable If the post process can be reused on the same frame. (default: false)
  58715. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  58716. * @param textureType Type of textures used when performing the post process. (default: 0)
  58717. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  58718. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  58719. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  58720. */
  58721. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  58722. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  58723. if (defines === void 0) { defines = null; }
  58724. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58725. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  58726. if (blockCompilation === void 0) { blockCompilation = false; }
  58727. this.name = name;
  58728. /**
  58729. * Width of the texture to apply the post process on
  58730. */
  58731. this.width = -1;
  58732. /**
  58733. * Height of the texture to apply the post process on
  58734. */
  58735. this.height = -1;
  58736. /**
  58737. * If the buffer needs to be cleared before applying the post process. (default: true)
  58738. * Should be set to false if shader will overwrite all previous pixels.
  58739. */
  58740. this.autoClear = true;
  58741. /**
  58742. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  58743. */
  58744. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  58745. /**
  58746. * Animations to be used for the post processing
  58747. */
  58748. this.animations = new Array();
  58749. /**
  58750. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  58751. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  58752. */
  58753. this.enablePixelPerfectMode = false;
  58754. /**
  58755. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  58756. */
  58757. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  58758. /**
  58759. * Force textures to be a power of two (default: false)
  58760. */
  58761. this.alwaysForcePOT = false;
  58762. /**
  58763. * Number of sample textures (default: 1)
  58764. */
  58765. this.samples = 1;
  58766. /**
  58767. * Modify the scale of the post process to be the same as the viewport (default: false)
  58768. */
  58769. this.adaptScaleToCurrentViewport = false;
  58770. this._reusable = false;
  58771. /**
  58772. * Smart array of input and output textures for the post process.
  58773. */
  58774. this._textures = new BABYLON.SmartArray(2);
  58775. /**
  58776. * The index in _textures that corresponds to the output texture.
  58777. */
  58778. this._currentRenderTextureInd = 0;
  58779. this._scaleRatio = new BABYLON.Vector2(1, 1);
  58780. this._texelSize = BABYLON.Vector2.Zero();
  58781. // Events
  58782. /**
  58783. * An event triggered when the postprocess is activated.
  58784. * @type {BABYLON.Observable}
  58785. */
  58786. this.onActivateObservable = new BABYLON.Observable();
  58787. /**
  58788. * An event triggered when the postprocess changes its size.
  58789. * @type {BABYLON.Observable}
  58790. */
  58791. this.onSizeChangedObservable = new BABYLON.Observable();
  58792. /**
  58793. * An event triggered when the postprocess applies its effect.
  58794. * @type {BABYLON.Observable}
  58795. */
  58796. this.onApplyObservable = new BABYLON.Observable();
  58797. /**
  58798. * An event triggered before rendering the postprocess
  58799. * @type {BABYLON.Observable}
  58800. */
  58801. this.onBeforeRenderObservable = new BABYLON.Observable();
  58802. /**
  58803. * An event triggered after rendering the postprocess
  58804. * @type {BABYLON.Observable}
  58805. */
  58806. this.onAfterRenderObservable = new BABYLON.Observable();
  58807. if (camera != null) {
  58808. this._camera = camera;
  58809. this._scene = camera.getScene();
  58810. camera.attachPostProcess(this);
  58811. this._engine = this._scene.getEngine();
  58812. this._scene.postProcesses.push(this);
  58813. }
  58814. else if (engine) {
  58815. this._engine = engine;
  58816. this._engine.postProcesses.push(this);
  58817. }
  58818. this._options = options;
  58819. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  58820. this._reusable = reusable || false;
  58821. this._textureType = textureType;
  58822. this._samplers = samplers || [];
  58823. this._samplers.push("textureSampler");
  58824. this._fragmentUrl = fragmentUrl;
  58825. this._vertexUrl = vertexUrl;
  58826. this._parameters = parameters || [];
  58827. this._parameters.push("scale");
  58828. this._indexParameters = indexParameters;
  58829. if (!blockCompilation) {
  58830. this.updateEffect(defines);
  58831. }
  58832. }
  58833. Object.defineProperty(PostProcess.prototype, "onActivate", {
  58834. /**
  58835. * A function that is added to the onActivateObservable
  58836. */
  58837. set: function (callback) {
  58838. if (this._onActivateObserver) {
  58839. this.onActivateObservable.remove(this._onActivateObserver);
  58840. }
  58841. if (callback) {
  58842. this._onActivateObserver = this.onActivateObservable.add(callback);
  58843. }
  58844. },
  58845. enumerable: true,
  58846. configurable: true
  58847. });
  58848. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  58849. /**
  58850. * A function that is added to the onSizeChangedObservable
  58851. */
  58852. set: function (callback) {
  58853. if (this._onSizeChangedObserver) {
  58854. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  58855. }
  58856. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  58857. },
  58858. enumerable: true,
  58859. configurable: true
  58860. });
  58861. Object.defineProperty(PostProcess.prototype, "onApply", {
  58862. /**
  58863. * A function that is added to the onApplyObservable
  58864. */
  58865. set: function (callback) {
  58866. if (this._onApplyObserver) {
  58867. this.onApplyObservable.remove(this._onApplyObserver);
  58868. }
  58869. this._onApplyObserver = this.onApplyObservable.add(callback);
  58870. },
  58871. enumerable: true,
  58872. configurable: true
  58873. });
  58874. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  58875. /**
  58876. * A function that is added to the onBeforeRenderObservable
  58877. */
  58878. set: function (callback) {
  58879. if (this._onBeforeRenderObserver) {
  58880. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58881. }
  58882. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58883. },
  58884. enumerable: true,
  58885. configurable: true
  58886. });
  58887. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  58888. /**
  58889. * A function that is added to the onAfterRenderObservable
  58890. */
  58891. set: function (callback) {
  58892. if (this._onAfterRenderObserver) {
  58893. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58894. }
  58895. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58896. },
  58897. enumerable: true,
  58898. configurable: true
  58899. });
  58900. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  58901. /**
  58902. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  58903. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  58904. */
  58905. get: function () {
  58906. return this._textures.data[this._currentRenderTextureInd];
  58907. },
  58908. set: function (value) {
  58909. this._forcedOutputTexture = value;
  58910. },
  58911. enumerable: true,
  58912. configurable: true
  58913. });
  58914. /**
  58915. * Gets the camera which post process is applied to.
  58916. * @returns The camera the post process is applied to.
  58917. */
  58918. PostProcess.prototype.getCamera = function () {
  58919. return this._camera;
  58920. };
  58921. Object.defineProperty(PostProcess.prototype, "texelSize", {
  58922. /**
  58923. * Gets the texel size of the postprocess.
  58924. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  58925. */
  58926. get: function () {
  58927. if (this._shareOutputWithPostProcess) {
  58928. return this._shareOutputWithPostProcess.texelSize;
  58929. }
  58930. if (this._forcedOutputTexture) {
  58931. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  58932. }
  58933. return this._texelSize;
  58934. },
  58935. enumerable: true,
  58936. configurable: true
  58937. });
  58938. /**
  58939. * Gets the engine which this post process belongs to.
  58940. * @returns The engine the post process was enabled with.
  58941. */
  58942. PostProcess.prototype.getEngine = function () {
  58943. return this._engine;
  58944. };
  58945. /**
  58946. * The effect that is created when initializing the post process.
  58947. * @returns The created effect corrisponding the the postprocess.
  58948. */
  58949. PostProcess.prototype.getEffect = function () {
  58950. return this._effect;
  58951. };
  58952. /**
  58953. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  58954. * @param postProcess The post process to share the output with.
  58955. * @returns This post process.
  58956. */
  58957. PostProcess.prototype.shareOutputWith = function (postProcess) {
  58958. this._disposeTextures();
  58959. this._shareOutputWithPostProcess = postProcess;
  58960. return this;
  58961. };
  58962. /**
  58963. * Updates the effect with the current post process compile time values and recompiles the shader.
  58964. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  58965. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  58966. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  58967. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  58968. * @param onCompiled Called when the shader has been compiled.
  58969. * @param onError Called if there is an error when compiling a shader.
  58970. */
  58971. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  58972. if (defines === void 0) { defines = null; }
  58973. if (uniforms === void 0) { uniforms = null; }
  58974. if (samplers === void 0) { samplers = null; }
  58975. 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);
  58976. };
  58977. /**
  58978. * The post process is reusable if it can be used multiple times within one frame.
  58979. * @returns If the post process is reusable
  58980. */
  58981. PostProcess.prototype.isReusable = function () {
  58982. return this._reusable;
  58983. };
  58984. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  58985. PostProcess.prototype.markTextureDirty = function () {
  58986. this.width = -1;
  58987. };
  58988. /**
  58989. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  58990. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  58991. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  58992. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  58993. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  58994. */
  58995. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  58996. var _this = this;
  58997. if (sourceTexture === void 0) { sourceTexture = null; }
  58998. camera = camera || this._camera;
  58999. var scene = camera.getScene();
  59000. var engine = scene.getEngine();
  59001. var maxSize = engine.getCaps().maxTextureSize;
  59002. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59003. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59004. var desiredWidth = (this._options.width || requiredWidth);
  59005. var desiredHeight = this._options.height || requiredHeight;
  59006. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59007. if (this.adaptScaleToCurrentViewport) {
  59008. var currentViewport = engine.currentViewport;
  59009. if (currentViewport) {
  59010. desiredWidth *= currentViewport.width;
  59011. desiredHeight *= currentViewport.height;
  59012. }
  59013. }
  59014. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59015. if (!this._options.width) {
  59016. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59017. }
  59018. if (!this._options.height) {
  59019. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59020. }
  59021. }
  59022. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59023. if (this._textures.length > 0) {
  59024. for (var i = 0; i < this._textures.length; i++) {
  59025. this._engine._releaseTexture(this._textures.data[i]);
  59026. }
  59027. this._textures.reset();
  59028. }
  59029. this.width = desiredWidth;
  59030. this.height = desiredHeight;
  59031. var textureSize = { width: this.width, height: this.height };
  59032. var textureOptions = {
  59033. generateMipMaps: false,
  59034. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59035. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59036. samplingMode: this.renderTargetSamplingMode,
  59037. type: this._textureType
  59038. };
  59039. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59040. if (this._reusable) {
  59041. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59042. }
  59043. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59044. this.onSizeChangedObservable.notifyObservers(this);
  59045. }
  59046. this._textures.forEach(function (texture) {
  59047. if (texture.samples !== _this.samples) {
  59048. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59049. }
  59050. });
  59051. }
  59052. var target;
  59053. if (this._shareOutputWithPostProcess) {
  59054. target = this._shareOutputWithPostProcess.inputTexture;
  59055. }
  59056. else if (this._forcedOutputTexture) {
  59057. target = this._forcedOutputTexture;
  59058. this.width = this._forcedOutputTexture.width;
  59059. this.height = this._forcedOutputTexture.height;
  59060. }
  59061. else {
  59062. target = this.inputTexture;
  59063. }
  59064. // Bind the input of this post process to be used as the output of the previous post process.
  59065. if (this.enablePixelPerfectMode) {
  59066. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59067. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59068. }
  59069. else {
  59070. this._scaleRatio.copyFromFloats(1, 1);
  59071. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59072. }
  59073. this.onActivateObservable.notifyObservers(camera);
  59074. // Clear
  59075. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59076. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59077. }
  59078. if (this._reusable) {
  59079. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59080. }
  59081. };
  59082. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59083. /**
  59084. * If the post process is supported.
  59085. */
  59086. get: function () {
  59087. return this._effect.isSupported;
  59088. },
  59089. enumerable: true,
  59090. configurable: true
  59091. });
  59092. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59093. /**
  59094. * The aspect ratio of the output texture.
  59095. */
  59096. get: function () {
  59097. if (this._shareOutputWithPostProcess) {
  59098. return this._shareOutputWithPostProcess.aspectRatio;
  59099. }
  59100. if (this._forcedOutputTexture) {
  59101. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59102. }
  59103. return this.width / this.height;
  59104. },
  59105. enumerable: true,
  59106. configurable: true
  59107. });
  59108. /**
  59109. * Get a value indicating if the post-process is ready to be used
  59110. * @returns true if the post-process is ready (shader is compiled)
  59111. */
  59112. PostProcess.prototype.isReady = function () {
  59113. return this._effect && this._effect.isReady();
  59114. };
  59115. /**
  59116. * Binds all textures and uniforms to the shader, this will be run on every pass.
  59117. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  59118. */
  59119. PostProcess.prototype.apply = function () {
  59120. // Check
  59121. if (!this._effect || !this._effect.isReady())
  59122. return null;
  59123. // States
  59124. this._engine.enableEffect(this._effect);
  59125. this._engine.setState(false);
  59126. this._engine.setDepthBuffer(false);
  59127. this._engine.setDepthWrite(false);
  59128. // Alpha
  59129. this._engine.setAlphaMode(this.alphaMode);
  59130. if (this.alphaConstants) {
  59131. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  59132. }
  59133. // Bind the output texture of the preivous post process as the input to this post process.
  59134. var source;
  59135. if (this._shareOutputWithPostProcess) {
  59136. source = this._shareOutputWithPostProcess.inputTexture;
  59137. }
  59138. else if (this._forcedOutputTexture) {
  59139. source = this._forcedOutputTexture;
  59140. }
  59141. else {
  59142. source = this.inputTexture;
  59143. }
  59144. this._effect._bindTexture("textureSampler", source);
  59145. // Parameters
  59146. this._effect.setVector2("scale", this._scaleRatio);
  59147. this.onApplyObservable.notifyObservers(this._effect);
  59148. return this._effect;
  59149. };
  59150. PostProcess.prototype._disposeTextures = function () {
  59151. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  59152. return;
  59153. }
  59154. if (this._textures.length > 0) {
  59155. for (var i = 0; i < this._textures.length; i++) {
  59156. this._engine._releaseTexture(this._textures.data[i]);
  59157. }
  59158. }
  59159. this._textures.dispose();
  59160. };
  59161. /**
  59162. * Disposes the post process.
  59163. * @param camera The camera to dispose the post process on.
  59164. */
  59165. PostProcess.prototype.dispose = function (camera) {
  59166. camera = camera || this._camera;
  59167. this._disposeTextures();
  59168. if (this._scene) {
  59169. var index_1 = this._scene.postProcesses.indexOf(this);
  59170. if (index_1 !== -1) {
  59171. this._scene.postProcesses.splice(index_1, 1);
  59172. }
  59173. }
  59174. else {
  59175. var index_2 = this._engine.postProcesses.indexOf(this);
  59176. if (index_2 !== -1) {
  59177. this._engine.postProcesses.splice(index_2, 1);
  59178. }
  59179. }
  59180. if (!camera) {
  59181. return;
  59182. }
  59183. camera.detachPostProcess(this);
  59184. var index = camera._postProcesses.indexOf(this);
  59185. if (index === 0 && camera._postProcesses.length > 0) {
  59186. this._camera._postProcesses[0].markTextureDirty();
  59187. }
  59188. this.onActivateObservable.clear();
  59189. this.onAfterRenderObservable.clear();
  59190. this.onApplyObservable.clear();
  59191. this.onBeforeRenderObservable.clear();
  59192. this.onSizeChangedObservable.clear();
  59193. };
  59194. return PostProcess;
  59195. }());
  59196. BABYLON.PostProcess = PostProcess;
  59197. })(BABYLON || (BABYLON = {}));
  59198. //# sourceMappingURL=babylon.postProcess.js.map
  59199. var BABYLON;
  59200. (function (BABYLON) {
  59201. var PassPostProcess = /** @class */ (function (_super) {
  59202. __extends(PassPostProcess, _super);
  59203. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59204. if (camera === void 0) { camera = null; }
  59205. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59206. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  59207. }
  59208. return PassPostProcess;
  59209. }(BABYLON.PostProcess));
  59210. BABYLON.PassPostProcess = PassPostProcess;
  59211. })(BABYLON || (BABYLON = {}));
  59212. //# sourceMappingURL=babylon.passPostProcess.js.map
  59213. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59214. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59215. s = arguments[i];
  59216. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59217. t[p] = s[p];
  59218. }
  59219. return t;
  59220. };
  59221. var BABYLON;
  59222. (function (BABYLON) {
  59223. /**
  59224. * Default implementation of @see IShadowGenerator.
  59225. * This is the main object responsible of generating shadows in the framework.
  59226. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  59227. */
  59228. var ShadowGenerator = /** @class */ (function () {
  59229. /**
  59230. * Creates a ShadowGenerator object.
  59231. * A ShadowGenerator is the required tool to use the shadows.
  59232. * Each light casting shadows needs to use its own ShadowGenerator.
  59233. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  59234. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  59235. * @param light The light object generating the shadows.
  59236. * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  59237. */
  59238. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59239. this._bias = 0.00005;
  59240. this._blurBoxOffset = 1;
  59241. this._blurScale = 2;
  59242. this._blurKernel = 1;
  59243. this._useKernelBlur = false;
  59244. this._filter = ShadowGenerator.FILTER_NONE;
  59245. this._darkness = 0;
  59246. this._transparencyShadow = false;
  59247. /**
  59248. * Controls the extent to which the shadows fade out at the edge of the frustum
  59249. * Used only by directionals and spots
  59250. */
  59251. this.frustumEdgeFalloff = 0;
  59252. /**
  59253. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59254. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59255. * It might on the other hand introduce peter panning.
  59256. */
  59257. this.forceBackFacesOnly = false;
  59258. this._lightDirection = BABYLON.Vector3.Zero();
  59259. this._viewMatrix = BABYLON.Matrix.Zero();
  59260. this._projectionMatrix = BABYLON.Matrix.Zero();
  59261. this._transformMatrix = BABYLON.Matrix.Zero();
  59262. this._currentFaceIndex = 0;
  59263. this._currentFaceIndexCache = 0;
  59264. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59265. this._mapSize = mapSize;
  59266. this._light = light;
  59267. this._scene = light.getScene();
  59268. light._shadowGenerator = this;
  59269. // Texture type fallback from float to int if not supported.
  59270. var caps = this._scene.getEngine().getCaps();
  59271. if (!useFullFloatFirst) {
  59272. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59273. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59274. }
  59275. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59276. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59277. }
  59278. else {
  59279. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59280. }
  59281. }
  59282. else {
  59283. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59284. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59285. }
  59286. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59287. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59288. }
  59289. else {
  59290. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59291. }
  59292. }
  59293. this._initializeGenerator();
  59294. }
  59295. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  59296. /**
  59297. * Shadow generator mode None: no filtering applied.
  59298. */
  59299. get: function () {
  59300. return ShadowGenerator._FILTER_NONE;
  59301. },
  59302. enumerable: true,
  59303. configurable: true
  59304. });
  59305. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  59306. /**
  59307. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  59308. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  59309. */
  59310. get: function () {
  59311. return ShadowGenerator._FILTER_POISSONSAMPLING;
  59312. },
  59313. enumerable: true,
  59314. configurable: true
  59315. });
  59316. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  59317. /**
  59318. * Shadow generator mode ESM: Exponential Shadow Mapping.
  59319. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59320. */
  59321. get: function () {
  59322. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  59323. },
  59324. enumerable: true,
  59325. configurable: true
  59326. });
  59327. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  59328. /**
  59329. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  59330. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59331. */
  59332. get: function () {
  59333. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  59334. },
  59335. enumerable: true,
  59336. configurable: true
  59337. });
  59338. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  59339. /**
  59340. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  59341. * edge artifacts on steep falloff.
  59342. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59343. */
  59344. get: function () {
  59345. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59346. },
  59347. enumerable: true,
  59348. configurable: true
  59349. });
  59350. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  59351. /**
  59352. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  59353. * edge artifacts on steep falloff.
  59354. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59355. */
  59356. get: function () {
  59357. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59358. },
  59359. enumerable: true,
  59360. configurable: true
  59361. });
  59362. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  59363. /**
  59364. * Gets the bias: offset applied on the depth preventing acnea.
  59365. */
  59366. get: function () {
  59367. return this._bias;
  59368. },
  59369. /**
  59370. * Sets the bias: offset applied on the depth preventing acnea.
  59371. */
  59372. set: function (bias) {
  59373. this._bias = bias;
  59374. },
  59375. enumerable: true,
  59376. configurable: true
  59377. });
  59378. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  59379. /**
  59380. * Gets the blur box offset: offset applied during the blur pass.
  59381. * Only usefull if useKernelBlur = false
  59382. */
  59383. get: function () {
  59384. return this._blurBoxOffset;
  59385. },
  59386. /**
  59387. * Sets the blur box offset: offset applied during the blur pass.
  59388. * Only usefull if useKernelBlur = false
  59389. */
  59390. set: function (value) {
  59391. if (this._blurBoxOffset === value) {
  59392. return;
  59393. }
  59394. this._blurBoxOffset = value;
  59395. this._disposeBlurPostProcesses();
  59396. },
  59397. enumerable: true,
  59398. configurable: true
  59399. });
  59400. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  59401. /**
  59402. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  59403. * 2 means half of the size.
  59404. */
  59405. get: function () {
  59406. return this._blurScale;
  59407. },
  59408. /**
  59409. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  59410. * 2 means half of the size.
  59411. */
  59412. set: function (value) {
  59413. if (this._blurScale === value) {
  59414. return;
  59415. }
  59416. this._blurScale = value;
  59417. this._disposeBlurPostProcesses();
  59418. },
  59419. enumerable: true,
  59420. configurable: true
  59421. });
  59422. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  59423. /**
  59424. * Gets the blur kernel: kernel size of the blur pass.
  59425. * Only usefull if useKernelBlur = true
  59426. */
  59427. get: function () {
  59428. return this._blurKernel;
  59429. },
  59430. /**
  59431. * Sets the blur kernel: kernel size of the blur pass.
  59432. * Only usefull if useKernelBlur = true
  59433. */
  59434. set: function (value) {
  59435. if (this._blurKernel === value) {
  59436. return;
  59437. }
  59438. this._blurKernel = value;
  59439. this._disposeBlurPostProcesses();
  59440. },
  59441. enumerable: true,
  59442. configurable: true
  59443. });
  59444. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  59445. /**
  59446. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  59447. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59448. */
  59449. get: function () {
  59450. return this._useKernelBlur;
  59451. },
  59452. /**
  59453. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  59454. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59455. */
  59456. set: function (value) {
  59457. if (this._useKernelBlur === value) {
  59458. return;
  59459. }
  59460. this._useKernelBlur = value;
  59461. this._disposeBlurPostProcesses();
  59462. },
  59463. enumerable: true,
  59464. configurable: true
  59465. });
  59466. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  59467. /**
  59468. * Gets the depth scale used in ESM mode.
  59469. */
  59470. get: function () {
  59471. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  59472. },
  59473. /**
  59474. * Sets the depth scale used in ESM mode.
  59475. * This can override the scale stored on the light.
  59476. */
  59477. set: function (value) {
  59478. this._depthScale = value;
  59479. },
  59480. enumerable: true,
  59481. configurable: true
  59482. });
  59483. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  59484. /**
  59485. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  59486. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59487. */
  59488. get: function () {
  59489. return this._filter;
  59490. },
  59491. /**
  59492. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  59493. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59494. */
  59495. set: function (value) {
  59496. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  59497. if (this._light.needCube()) {
  59498. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59499. this.useExponentialShadowMap = true;
  59500. return;
  59501. }
  59502. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59503. this.useCloseExponentialShadowMap = true;
  59504. return;
  59505. }
  59506. }
  59507. if (this._filter === value) {
  59508. return;
  59509. }
  59510. this._filter = value;
  59511. this._disposeBlurPostProcesses();
  59512. this._applyFilterValues();
  59513. this._light._markMeshesAsLightDirty();
  59514. },
  59515. enumerable: true,
  59516. configurable: true
  59517. });
  59518. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  59519. /**
  59520. * Gets if the current filter is set to Poisson Sampling aka PCF.
  59521. */
  59522. get: function () {
  59523. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  59524. },
  59525. /**
  59526. * Sets the current filter to Poisson Sampling aka PCF.
  59527. */
  59528. set: function (value) {
  59529. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  59530. return;
  59531. }
  59532. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  59533. },
  59534. enumerable: true,
  59535. configurable: true
  59536. });
  59537. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  59538. /**
  59539. * Gets if the current filter is set to VSM.
  59540. * DEPRECATED. Should use useExponentialShadowMap instead.
  59541. */
  59542. get: function () {
  59543. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59544. return this.useExponentialShadowMap;
  59545. },
  59546. /**
  59547. * Sets the current filter is to VSM.
  59548. * DEPRECATED. Should use useExponentialShadowMap instead.
  59549. */
  59550. set: function (value) {
  59551. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59552. this.useExponentialShadowMap = value;
  59553. },
  59554. enumerable: true,
  59555. configurable: true
  59556. });
  59557. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  59558. /**
  59559. * Gets if the current filter is set to blurred VSM.
  59560. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59561. */
  59562. get: function () {
  59563. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59564. return this.useBlurExponentialShadowMap;
  59565. },
  59566. /**
  59567. * Sets the current filter is to blurred VSM.
  59568. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59569. */
  59570. set: function (value) {
  59571. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59572. this.useBlurExponentialShadowMap = value;
  59573. },
  59574. enumerable: true,
  59575. configurable: true
  59576. });
  59577. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  59578. /**
  59579. * Gets if the current filter is set to ESM.
  59580. */
  59581. get: function () {
  59582. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  59583. },
  59584. /**
  59585. * Sets the current filter is to ESM.
  59586. */
  59587. set: function (value) {
  59588. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  59589. return;
  59590. }
  59591. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59592. },
  59593. enumerable: true,
  59594. configurable: true
  59595. });
  59596. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  59597. /**
  59598. * Gets if the current filter is set to filtered ESM.
  59599. */
  59600. get: function () {
  59601. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  59602. },
  59603. /**
  59604. * Gets if the current filter is set to filtered ESM.
  59605. */
  59606. set: function (value) {
  59607. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59608. return;
  59609. }
  59610. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59611. },
  59612. enumerable: true,
  59613. configurable: true
  59614. });
  59615. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  59616. /**
  59617. * Gets if the current filter is set to "close ESM" (using the inverse of the
  59618. * exponential to prevent steep falloff artifacts).
  59619. */
  59620. get: function () {
  59621. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59622. },
  59623. /**
  59624. * Sets the current filter to "close ESM" (using the inverse of the
  59625. * exponential to prevent steep falloff artifacts).
  59626. */
  59627. set: function (value) {
  59628. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  59629. return;
  59630. }
  59631. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59632. },
  59633. enumerable: true,
  59634. configurable: true
  59635. });
  59636. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  59637. /**
  59638. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  59639. * exponential to prevent steep falloff artifacts).
  59640. */
  59641. get: function () {
  59642. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59643. },
  59644. /**
  59645. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  59646. * exponential to prevent steep falloff artifacts).
  59647. */
  59648. set: function (value) {
  59649. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59650. return;
  59651. }
  59652. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59653. },
  59654. enumerable: true,
  59655. configurable: true
  59656. });
  59657. /**
  59658. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  59659. * 0 means strongest and 1 would means no shadow.
  59660. * @returns the darkness.
  59661. */
  59662. ShadowGenerator.prototype.getDarkness = function () {
  59663. return this._darkness;
  59664. };
  59665. /**
  59666. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  59667. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  59668. * @returns the shadow generator allowing fluent coding.
  59669. */
  59670. ShadowGenerator.prototype.setDarkness = function (darkness) {
  59671. if (darkness >= 1.0)
  59672. this._darkness = 1.0;
  59673. else if (darkness <= 0.0)
  59674. this._darkness = 0.0;
  59675. else
  59676. this._darkness = darkness;
  59677. return this;
  59678. };
  59679. /**
  59680. * Sets the ability to have transparent shadow (boolean).
  59681. * @param transparent True if transparent else False
  59682. * @returns the shadow generator allowing fluent coding
  59683. */
  59684. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  59685. this._transparencyShadow = transparent;
  59686. return this;
  59687. };
  59688. /**
  59689. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  59690. * @returns The render target texture if present otherwise, null
  59691. */
  59692. ShadowGenerator.prototype.getShadowMap = function () {
  59693. return this._shadowMap;
  59694. };
  59695. /**
  59696. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  59697. * @returns The render target texture if the shadow map is present otherwise, null
  59698. */
  59699. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  59700. if (this._shadowMap2) {
  59701. return this._shadowMap2;
  59702. }
  59703. return this._shadowMap;
  59704. };
  59705. /**
  59706. * Helper function to add a mesh and its descendants to the list of shadow casters.
  59707. * @param mesh Mesh to add
  59708. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  59709. * @returns the Shadow Generator itself
  59710. */
  59711. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  59712. if (includeDescendants === void 0) { includeDescendants = true; }
  59713. if (!this._shadowMap) {
  59714. return this;
  59715. }
  59716. if (!this._shadowMap.renderList) {
  59717. this._shadowMap.renderList = [];
  59718. }
  59719. this._shadowMap.renderList.push(mesh);
  59720. if (includeDescendants) {
  59721. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  59722. }
  59723. return this;
  59724. var _a;
  59725. };
  59726. /**
  59727. * Helper function to remove a mesh and its descendants from the list of shadow casters
  59728. * @param mesh Mesh to remove
  59729. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  59730. * @returns the Shadow Generator itself
  59731. */
  59732. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  59733. if (includeDescendants === void 0) { includeDescendants = true; }
  59734. if (!this._shadowMap || !this._shadowMap.renderList) {
  59735. return this;
  59736. }
  59737. var index = this._shadowMap.renderList.indexOf(mesh);
  59738. if (index !== -1) {
  59739. this._shadowMap.renderList.splice(index, 1);
  59740. }
  59741. if (includeDescendants) {
  59742. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  59743. var child = _a[_i];
  59744. this.removeShadowCaster(child);
  59745. }
  59746. }
  59747. return this;
  59748. };
  59749. /**
  59750. * Returns the associated light object.
  59751. * @returns the light generating the shadow
  59752. */
  59753. ShadowGenerator.prototype.getLight = function () {
  59754. return this._light;
  59755. };
  59756. ShadowGenerator.prototype._initializeGenerator = function () {
  59757. this._light._markMeshesAsLightDirty();
  59758. this._initializeShadowMap();
  59759. };
  59760. ShadowGenerator.prototype._initializeShadowMap = function () {
  59761. var _this = this;
  59762. // Render target
  59763. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  59764. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59765. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59766. this._shadowMap.anisotropicFilteringLevel = 1;
  59767. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59768. this._shadowMap.renderParticles = false;
  59769. this._shadowMap.ignoreCameraViewport = true;
  59770. // Record Face Index before render.
  59771. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  59772. _this._currentFaceIndex = faceIndex;
  59773. });
  59774. // Custom render function.
  59775. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  59776. // Blur if required afer render.
  59777. this._shadowMap.onAfterUnbindObservable.add(function () {
  59778. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  59779. return;
  59780. }
  59781. var shadowMap = _this.getShadowMapForRendering();
  59782. if (shadowMap) {
  59783. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  59784. }
  59785. });
  59786. // Clear according to the chosen filter.
  59787. this._shadowMap.onClearObservable.add(function (engine) {
  59788. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  59789. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  59790. }
  59791. else {
  59792. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59793. }
  59794. });
  59795. };
  59796. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  59797. var _this = this;
  59798. var engine = this._scene.getEngine();
  59799. var targetSize = this._mapSize / this.blurScale;
  59800. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  59801. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  59802. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59803. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59804. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59805. }
  59806. if (this.useKernelBlur) {
  59807. 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);
  59808. this._kernelBlurXPostprocess.width = targetSize;
  59809. this._kernelBlurXPostprocess.height = targetSize;
  59810. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  59811. effect.setTexture("textureSampler", _this._shadowMap);
  59812. });
  59813. 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);
  59814. this._kernelBlurXPostprocess.autoClear = false;
  59815. this._kernelBlurYPostprocess.autoClear = false;
  59816. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59817. this._kernelBlurXPostprocess.packedFloat = true;
  59818. this._kernelBlurYPostprocess.packedFloat = true;
  59819. }
  59820. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  59821. }
  59822. else {
  59823. 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);
  59824. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  59825. effect.setFloat2("screenSize", targetSize, targetSize);
  59826. effect.setTexture("textureSampler", _this._shadowMap);
  59827. });
  59828. this._boxBlurPostprocess.autoClear = false;
  59829. this._blurPostProcesses = [this._boxBlurPostprocess];
  59830. }
  59831. };
  59832. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59833. var index;
  59834. var engine = this._scene.getEngine();
  59835. if (depthOnlySubMeshes.length) {
  59836. engine.setColorWrite(false);
  59837. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59838. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  59839. }
  59840. engine.setColorWrite(true);
  59841. }
  59842. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59843. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  59844. }
  59845. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59846. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  59847. }
  59848. if (this._transparencyShadow) {
  59849. for (index = 0; index < transparentSubMeshes.length; index++) {
  59850. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  59851. }
  59852. }
  59853. };
  59854. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  59855. var _this = this;
  59856. var mesh = subMesh.getRenderingMesh();
  59857. var scene = this._scene;
  59858. var engine = scene.getEngine();
  59859. var material = subMesh.getMaterial();
  59860. if (!material) {
  59861. return;
  59862. }
  59863. // Culling
  59864. engine.setState(material.backFaceCulling);
  59865. // Managing instances
  59866. var batch = mesh._getInstancesRenderList(subMesh._id);
  59867. if (batch.mustReturn) {
  59868. return;
  59869. }
  59870. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  59871. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  59872. engine.enableEffect(this._effect);
  59873. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  59874. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  59875. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  59876. this._effect.setVector3("lightPosition", this.getLight().position);
  59877. if (scene.activeCamera) {
  59878. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  59879. }
  59880. // Alpha test
  59881. if (material && material.needAlphaTesting()) {
  59882. var alphaTexture = material.getAlphaTestTexture();
  59883. if (alphaTexture) {
  59884. this._effect.setTexture("diffuseSampler", alphaTexture);
  59885. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  59886. }
  59887. }
  59888. // Bones
  59889. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59890. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  59891. }
  59892. if (this.forceBackFacesOnly) {
  59893. engine.setState(true, 0, false, true);
  59894. }
  59895. // Draw
  59896. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59897. if (this.forceBackFacesOnly) {
  59898. engine.setState(true, 0, false, false);
  59899. }
  59900. }
  59901. else {
  59902. // Need to reset refresh rate of the shadowMap
  59903. if (this._shadowMap) {
  59904. this._shadowMap.resetRefreshCounter();
  59905. }
  59906. }
  59907. };
  59908. ShadowGenerator.prototype._applyFilterValues = function () {
  59909. if (!this._shadowMap) {
  59910. return;
  59911. }
  59912. if (this.filter === ShadowGenerator.FILTER_NONE) {
  59913. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59914. }
  59915. else {
  59916. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59917. }
  59918. };
  59919. /**
  59920. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59921. * @param onCompiled Callback triggered at the and of the effects compilation
  59922. * @param options Sets of optional options forcing the compilation with different modes
  59923. */
  59924. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  59925. var _this = this;
  59926. var localOptions = __assign({ useInstances: false }, options);
  59927. var shadowMap = this.getShadowMap();
  59928. if (!shadowMap) {
  59929. if (onCompiled) {
  59930. onCompiled(this);
  59931. }
  59932. return;
  59933. }
  59934. var renderList = shadowMap.renderList;
  59935. if (!renderList) {
  59936. if (onCompiled) {
  59937. onCompiled(this);
  59938. }
  59939. return;
  59940. }
  59941. var subMeshes = new Array();
  59942. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  59943. var mesh = renderList_1[_i];
  59944. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  59945. }
  59946. if (subMeshes.length === 0) {
  59947. if (onCompiled) {
  59948. onCompiled(this);
  59949. }
  59950. return;
  59951. }
  59952. var currentIndex = 0;
  59953. var checkReady = function () {
  59954. if (!_this._scene || !_this._scene.getEngine()) {
  59955. return;
  59956. }
  59957. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  59958. currentIndex++;
  59959. if (currentIndex >= subMeshes.length) {
  59960. if (onCompiled) {
  59961. onCompiled(_this);
  59962. }
  59963. return;
  59964. }
  59965. }
  59966. setTimeout(checkReady, 16);
  59967. };
  59968. checkReady();
  59969. };
  59970. /**
  59971. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59972. * @param options Sets of optional options forcing the compilation with different modes
  59973. * @returns A promise that resolves when the compilation completes
  59974. */
  59975. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  59976. var _this = this;
  59977. return new Promise(function (resolve) {
  59978. _this.forceCompilation(function () {
  59979. resolve();
  59980. }, options);
  59981. });
  59982. };
  59983. /**
  59984. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  59985. * @param subMesh The submesh we want to render in the shadow map
  59986. * @param useInstances Defines wether will draw in the map using instances
  59987. * @returns true if ready otherwise, false
  59988. */
  59989. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  59990. var defines = [];
  59991. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59992. defines.push("#define FLOAT");
  59993. }
  59994. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59995. defines.push("#define ESM");
  59996. }
  59997. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59998. var mesh = subMesh.getMesh();
  59999. var material = subMesh.getMaterial();
  60000. // Alpha test
  60001. if (material && material.needAlphaTesting()) {
  60002. var alphaTexture = material.getAlphaTestTexture();
  60003. if (alphaTexture) {
  60004. defines.push("#define ALPHATEST");
  60005. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60006. attribs.push(BABYLON.VertexBuffer.UVKind);
  60007. defines.push("#define UV1");
  60008. }
  60009. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60010. if (alphaTexture.coordinatesIndex === 1) {
  60011. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60012. defines.push("#define UV2");
  60013. }
  60014. }
  60015. }
  60016. }
  60017. // Bones
  60018. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60019. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60020. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60021. if (mesh.numBoneInfluencers > 4) {
  60022. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60023. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60024. }
  60025. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60026. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60027. }
  60028. else {
  60029. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60030. }
  60031. // Instances
  60032. if (useInstances) {
  60033. defines.push("#define INSTANCES");
  60034. attribs.push("world0");
  60035. attribs.push("world1");
  60036. attribs.push("world2");
  60037. attribs.push("world3");
  60038. }
  60039. // Get correct effect
  60040. var join = defines.join("\n");
  60041. if (this._cachedDefines !== join) {
  60042. this._cachedDefines = join;
  60043. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  60044. }
  60045. if (!this._effect.isReady()) {
  60046. return false;
  60047. }
  60048. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60049. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  60050. this._initializeBlurRTTAndPostProcesses();
  60051. }
  60052. }
  60053. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  60054. return false;
  60055. }
  60056. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  60057. return false;
  60058. }
  60059. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  60060. return false;
  60061. }
  60062. return true;
  60063. };
  60064. /**
  60065. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  60066. * @param defines Defines of the material we want to update
  60067. * @param lightIndex Index of the light in the enabled light list of the material
  60068. */
  60069. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  60070. var scene = this._scene;
  60071. var light = this._light;
  60072. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60073. return;
  60074. }
  60075. defines["SHADOW" + lightIndex] = true;
  60076. if (this.usePoissonSampling) {
  60077. defines["SHADOWPCF" + lightIndex] = true;
  60078. }
  60079. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60080. defines["SHADOWESM" + lightIndex] = true;
  60081. }
  60082. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60083. defines["SHADOWCLOSEESM" + lightIndex] = true;
  60084. }
  60085. if (light.needCube()) {
  60086. defines["SHADOWCUBE" + lightIndex] = true;
  60087. }
  60088. };
  60089. /**
  60090. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60091. * defined in the generator but impacting the effect).
  60092. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60093. * @param effect The effect we are binfing the information for
  60094. */
  60095. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60096. var light = this._light;
  60097. var scene = this._scene;
  60098. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60099. return;
  60100. }
  60101. var camera = scene.activeCamera;
  60102. if (!camera) {
  60103. return;
  60104. }
  60105. var shadowMap = this.getShadowMap();
  60106. if (!shadowMap) {
  60107. return;
  60108. }
  60109. if (!light.needCube()) {
  60110. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  60111. }
  60112. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  60113. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  60114. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  60115. };
  60116. /**
  60117. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  60118. * (eq to shadow prjection matrix * light transform matrix)
  60119. * @returns The transform matrix used to create the shadow map
  60120. */
  60121. ShadowGenerator.prototype.getTransformMatrix = function () {
  60122. var scene = this._scene;
  60123. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  60124. return this._transformMatrix;
  60125. }
  60126. this._currentRenderID = scene.getRenderId();
  60127. this._currentFaceIndexCache = this._currentFaceIndex;
  60128. var lightPosition = this._light.position;
  60129. if (this._light.computeTransformedInformation()) {
  60130. lightPosition = this._light.transformedPosition;
  60131. }
  60132. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  60133. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  60134. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  60135. }
  60136. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  60137. this._cachedPosition = lightPosition.clone();
  60138. this._cachedDirection = this._lightDirection.clone();
  60139. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  60140. var shadowMap = this.getShadowMap();
  60141. if (shadowMap) {
  60142. var renderList = shadowMap.renderList;
  60143. if (renderList) {
  60144. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  60145. }
  60146. }
  60147. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  60148. }
  60149. return this._transformMatrix;
  60150. };
  60151. /**
  60152. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  60153. * Cube and 2D textures for instance.
  60154. */
  60155. ShadowGenerator.prototype.recreateShadowMap = function () {
  60156. var shadowMap = this._shadowMap;
  60157. if (!shadowMap) {
  60158. return;
  60159. }
  60160. // Track render list.
  60161. var renderList = shadowMap.renderList;
  60162. // Clean up existing data.
  60163. this._disposeRTTandPostProcesses();
  60164. // Reinitializes.
  60165. this._initializeGenerator();
  60166. // Reaffect the filter to ensure a correct fallback if necessary.
  60167. this.filter = this.filter;
  60168. // Reaffect the filter.
  60169. this._applyFilterValues();
  60170. // Reaffect Render List.
  60171. this._shadowMap.renderList = renderList;
  60172. };
  60173. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  60174. if (this._shadowMap2) {
  60175. this._shadowMap2.dispose();
  60176. this._shadowMap2 = null;
  60177. }
  60178. if (this._boxBlurPostprocess) {
  60179. this._boxBlurPostprocess.dispose();
  60180. this._boxBlurPostprocess = null;
  60181. }
  60182. if (this._kernelBlurXPostprocess) {
  60183. this._kernelBlurXPostprocess.dispose();
  60184. this._kernelBlurXPostprocess = null;
  60185. }
  60186. if (this._kernelBlurYPostprocess) {
  60187. this._kernelBlurYPostprocess.dispose();
  60188. this._kernelBlurYPostprocess = null;
  60189. }
  60190. this._blurPostProcesses = [];
  60191. };
  60192. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  60193. if (this._shadowMap) {
  60194. this._shadowMap.dispose();
  60195. this._shadowMap = null;
  60196. }
  60197. this._disposeBlurPostProcesses();
  60198. };
  60199. /**
  60200. * Disposes the ShadowGenerator.
  60201. * Returns nothing.
  60202. */
  60203. ShadowGenerator.prototype.dispose = function () {
  60204. this._disposeRTTandPostProcesses();
  60205. if (this._light) {
  60206. this._light._shadowGenerator = null;
  60207. this._light._markMeshesAsLightDirty();
  60208. }
  60209. };
  60210. /**
  60211. * Serializes the shadow generator setup to a json object.
  60212. * @returns The serialized JSON object
  60213. */
  60214. ShadowGenerator.prototype.serialize = function () {
  60215. var serializationObject = {};
  60216. var shadowMap = this.getShadowMap();
  60217. if (!shadowMap) {
  60218. return serializationObject;
  60219. }
  60220. serializationObject.lightId = this._light.id;
  60221. serializationObject.mapSize = shadowMap.getRenderSize();
  60222. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  60223. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  60224. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60225. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60226. serializationObject.usePoissonSampling = this.usePoissonSampling;
  60227. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  60228. serializationObject.depthScale = this.depthScale;
  60229. serializationObject.darkness = this.getDarkness();
  60230. serializationObject.blurBoxOffset = this.blurBoxOffset;
  60231. serializationObject.blurKernel = this.blurKernel;
  60232. serializationObject.blurScale = this.blurScale;
  60233. serializationObject.useKernelBlur = this.useKernelBlur;
  60234. serializationObject.transparencyShadow = this._transparencyShadow;
  60235. serializationObject.renderList = [];
  60236. if (shadowMap.renderList) {
  60237. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60238. var mesh = shadowMap.renderList[meshIndex];
  60239. serializationObject.renderList.push(mesh.id);
  60240. }
  60241. }
  60242. return serializationObject;
  60243. };
  60244. /**
  60245. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60246. * @param parsedShadowGenerator The JSON object to parse
  60247. * @param scene The scene to create the shadow map for
  60248. * @returns The parsed shadow generator
  60249. */
  60250. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60251. //casting to point light, as light is missing the position attr and typescript complains.
  60252. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60253. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60254. var shadowMap = shadowGenerator.getShadowMap();
  60255. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60256. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60257. meshes.forEach(function (mesh) {
  60258. if (!shadowMap) {
  60259. return;
  60260. }
  60261. if (!shadowMap.renderList) {
  60262. shadowMap.renderList = [];
  60263. }
  60264. shadowMap.renderList.push(mesh);
  60265. });
  60266. }
  60267. if (parsedShadowGenerator.usePoissonSampling) {
  60268. shadowGenerator.usePoissonSampling = true;
  60269. }
  60270. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60271. shadowGenerator.useExponentialShadowMap = true;
  60272. }
  60273. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  60274. shadowGenerator.useBlurExponentialShadowMap = true;
  60275. }
  60276. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  60277. shadowGenerator.useCloseExponentialShadowMap = true;
  60278. }
  60279. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  60280. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  60281. }
  60282. else if (parsedShadowGenerator.useVarianceShadowMap) {
  60283. shadowGenerator.useExponentialShadowMap = true;
  60284. }
  60285. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  60286. shadowGenerator.useBlurExponentialShadowMap = true;
  60287. }
  60288. if (parsedShadowGenerator.depthScale) {
  60289. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  60290. }
  60291. if (parsedShadowGenerator.blurScale) {
  60292. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  60293. }
  60294. if (parsedShadowGenerator.blurBoxOffset) {
  60295. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  60296. }
  60297. if (parsedShadowGenerator.useKernelBlur) {
  60298. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  60299. }
  60300. if (parsedShadowGenerator.blurKernel) {
  60301. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  60302. }
  60303. if (parsedShadowGenerator.bias !== undefined) {
  60304. shadowGenerator.bias = parsedShadowGenerator.bias;
  60305. }
  60306. if (parsedShadowGenerator.darkness) {
  60307. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  60308. }
  60309. if (parsedShadowGenerator.transparencyShadow) {
  60310. shadowGenerator.setTransparencyShadow(true);
  60311. }
  60312. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  60313. return shadowGenerator;
  60314. };
  60315. ShadowGenerator._FILTER_NONE = 0;
  60316. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  60317. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  60318. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  60319. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  60320. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  60321. return ShadowGenerator;
  60322. }());
  60323. BABYLON.ShadowGenerator = ShadowGenerator;
  60324. })(BABYLON || (BABYLON = {}));
  60325. //# sourceMappingURL=babylon.shadowGenerator.js.map
  60326. var BABYLON;
  60327. (function (BABYLON) {
  60328. var DefaultLoadingScreen = /** @class */ (function () {
  60329. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  60330. if (_loadingText === void 0) { _loadingText = ""; }
  60331. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  60332. var _this = this;
  60333. this._renderingCanvas = _renderingCanvas;
  60334. this._loadingText = _loadingText;
  60335. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  60336. // Resize
  60337. this._resizeLoadingUI = function () {
  60338. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  60339. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  60340. if (!_this._loadingDiv) {
  60341. return;
  60342. }
  60343. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  60344. _this._loadingDiv.style.left = canvasRect.left + "px";
  60345. _this._loadingDiv.style.top = canvasRect.top + "px";
  60346. _this._loadingDiv.style.width = canvasRect.width + "px";
  60347. _this._loadingDiv.style.height = canvasRect.height + "px";
  60348. };
  60349. }
  60350. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  60351. if (this._loadingDiv) {
  60352. // Do not add a loading screen if there is already one
  60353. return;
  60354. }
  60355. this._loadingDiv = document.createElement("div");
  60356. this._loadingDiv.id = "babylonjsLoadingDiv";
  60357. this._loadingDiv.style.opacity = "0";
  60358. this._loadingDiv.style.transition = "opacity 1.5s ease";
  60359. this._loadingDiv.style.pointerEvents = "none";
  60360. // Loading text
  60361. this._loadingTextDiv = document.createElement("div");
  60362. this._loadingTextDiv.style.position = "absolute";
  60363. this._loadingTextDiv.style.left = "0";
  60364. this._loadingTextDiv.style.top = "50%";
  60365. this._loadingTextDiv.style.marginTop = "80px";
  60366. this._loadingTextDiv.style.width = "100%";
  60367. this._loadingTextDiv.style.height = "20px";
  60368. this._loadingTextDiv.style.fontFamily = "Arial";
  60369. this._loadingTextDiv.style.fontSize = "14px";
  60370. this._loadingTextDiv.style.color = "white";
  60371. this._loadingTextDiv.style.textAlign = "center";
  60372. this._loadingTextDiv.innerHTML = "Loading";
  60373. this._loadingDiv.appendChild(this._loadingTextDiv);
  60374. //set the predefined text
  60375. this._loadingTextDiv.innerHTML = this._loadingText;
  60376. // Generating keyframes
  60377. var style = document.createElement('style');
  60378. style.type = 'text/css';
  60379. 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 }";
  60380. style.innerHTML = keyFrames;
  60381. document.getElementsByTagName('head')[0].appendChild(style);
  60382. // Loading img
  60383. var imgBack = new Image();
  60384. 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";
  60385. imgBack.style.position = "absolute";
  60386. imgBack.style.left = "50%";
  60387. imgBack.style.top = "50%";
  60388. imgBack.style.marginLeft = "-60px";
  60389. imgBack.style.marginTop = "-60px";
  60390. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  60391. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  60392. imgBack.style.transformOrigin = "50% 50%";
  60393. imgBack.style.webkitTransformOrigin = "50% 50%";
  60394. this._loadingDiv.appendChild(imgBack);
  60395. this._resizeLoadingUI();
  60396. window.addEventListener("resize", this._resizeLoadingUI);
  60397. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60398. document.body.appendChild(this._loadingDiv);
  60399. this._loadingDiv.style.opacity = "1";
  60400. };
  60401. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  60402. var _this = this;
  60403. if (!this._loadingDiv) {
  60404. return;
  60405. }
  60406. var onTransitionEnd = function () {
  60407. if (!_this._loadingDiv) {
  60408. return;
  60409. }
  60410. document.body.removeChild(_this._loadingDiv);
  60411. window.removeEventListener("resize", _this._resizeLoadingUI);
  60412. _this._loadingDiv = null;
  60413. };
  60414. this._loadingDiv.style.opacity = "0";
  60415. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  60416. };
  60417. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  60418. set: function (text) {
  60419. this._loadingText = text;
  60420. if (this._loadingTextDiv) {
  60421. this._loadingTextDiv.innerHTML = this._loadingText;
  60422. }
  60423. },
  60424. enumerable: true,
  60425. configurable: true
  60426. });
  60427. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  60428. get: function () {
  60429. return this._loadingDivBackgroundColor;
  60430. },
  60431. set: function (color) {
  60432. this._loadingDivBackgroundColor = color;
  60433. if (!this._loadingDiv) {
  60434. return;
  60435. }
  60436. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60437. },
  60438. enumerable: true,
  60439. configurable: true
  60440. });
  60441. return DefaultLoadingScreen;
  60442. }());
  60443. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  60444. })(BABYLON || (BABYLON = {}));
  60445. //# sourceMappingURL=babylon.loadingScreen.js.map
  60446. var BABYLON;
  60447. (function (BABYLON) {
  60448. var SceneLoaderProgressEvent = /** @class */ (function () {
  60449. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  60450. this.lengthComputable = lengthComputable;
  60451. this.loaded = loaded;
  60452. this.total = total;
  60453. }
  60454. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  60455. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  60456. };
  60457. return SceneLoaderProgressEvent;
  60458. }());
  60459. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  60460. var SceneLoader = /** @class */ (function () {
  60461. function SceneLoader() {
  60462. }
  60463. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  60464. get: function () {
  60465. return 0;
  60466. },
  60467. enumerable: true,
  60468. configurable: true
  60469. });
  60470. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  60471. get: function () {
  60472. return 1;
  60473. },
  60474. enumerable: true,
  60475. configurable: true
  60476. });
  60477. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  60478. get: function () {
  60479. return 2;
  60480. },
  60481. enumerable: true,
  60482. configurable: true
  60483. });
  60484. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  60485. get: function () {
  60486. return 3;
  60487. },
  60488. enumerable: true,
  60489. configurable: true
  60490. });
  60491. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  60492. get: function () {
  60493. return SceneLoader._ForceFullSceneLoadingForIncremental;
  60494. },
  60495. set: function (value) {
  60496. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  60497. },
  60498. enumerable: true,
  60499. configurable: true
  60500. });
  60501. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  60502. get: function () {
  60503. return SceneLoader._ShowLoadingScreen;
  60504. },
  60505. set: function (value) {
  60506. SceneLoader._ShowLoadingScreen = value;
  60507. },
  60508. enumerable: true,
  60509. configurable: true
  60510. });
  60511. Object.defineProperty(SceneLoader, "loggingLevel", {
  60512. get: function () {
  60513. return SceneLoader._loggingLevel;
  60514. },
  60515. set: function (value) {
  60516. SceneLoader._loggingLevel = value;
  60517. },
  60518. enumerable: true,
  60519. configurable: true
  60520. });
  60521. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  60522. get: function () {
  60523. return SceneLoader._CleanBoneMatrixWeights;
  60524. },
  60525. set: function (value) {
  60526. SceneLoader._CleanBoneMatrixWeights = value;
  60527. },
  60528. enumerable: true,
  60529. configurable: true
  60530. });
  60531. SceneLoader._getDefaultPlugin = function () {
  60532. return SceneLoader._registeredPlugins[".babylon"];
  60533. };
  60534. SceneLoader._getPluginForExtension = function (extension) {
  60535. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  60536. if (registeredPlugin) {
  60537. return registeredPlugin;
  60538. }
  60539. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  60540. return SceneLoader._getDefaultPlugin();
  60541. };
  60542. SceneLoader._getPluginForDirectLoad = function (data) {
  60543. for (var extension in SceneLoader._registeredPlugins) {
  60544. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  60545. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  60546. return SceneLoader._registeredPlugins[extension];
  60547. }
  60548. }
  60549. return SceneLoader._getDefaultPlugin();
  60550. };
  60551. SceneLoader._getPluginForFilename = function (sceneFilename) {
  60552. if (sceneFilename.name) {
  60553. sceneFilename = sceneFilename.name;
  60554. }
  60555. var queryStringPosition = sceneFilename.indexOf("?");
  60556. if (queryStringPosition !== -1) {
  60557. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  60558. }
  60559. var dotPosition = sceneFilename.lastIndexOf(".");
  60560. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  60561. return SceneLoader._getPluginForExtension(extension);
  60562. };
  60563. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  60564. SceneLoader._getDirectLoad = function (sceneFilename) {
  60565. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  60566. return sceneFilename.substr(5);
  60567. }
  60568. return null;
  60569. };
  60570. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  60571. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  60572. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  60573. var plugin;
  60574. if (registeredPlugin.plugin.createPlugin) {
  60575. plugin = registeredPlugin.plugin.createPlugin();
  60576. }
  60577. else {
  60578. plugin = registeredPlugin.plugin;
  60579. }
  60580. var useArrayBuffer = registeredPlugin.isBinary;
  60581. var database;
  60582. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  60583. var dataCallback = function (data, responseURL) {
  60584. if (scene.isDisposed) {
  60585. onError("Scene has been disposed");
  60586. return;
  60587. }
  60588. scene.database = database;
  60589. onSuccess(plugin, data, responseURL);
  60590. };
  60591. var request = null;
  60592. var pluginDisposed = false;
  60593. var onDisposeObservable = plugin.onDisposeObservable;
  60594. if (onDisposeObservable) {
  60595. onDisposeObservable.add(function () {
  60596. pluginDisposed = true;
  60597. if (request) {
  60598. request.abort();
  60599. request = null;
  60600. }
  60601. onDispose();
  60602. });
  60603. }
  60604. var manifestChecked = function () {
  60605. if (pluginDisposed) {
  60606. return;
  60607. }
  60608. var url = rootUrl + sceneFilename;
  60609. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  60610. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  60611. } : undefined, database, useArrayBuffer, function (request, exception) {
  60612. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  60613. });
  60614. };
  60615. if (directLoad) {
  60616. dataCallback(directLoad);
  60617. return plugin;
  60618. }
  60619. if (rootUrl.indexOf("file:") === -1) {
  60620. if (scene.getEngine().enableOfflineSupport) {
  60621. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  60622. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  60623. }
  60624. else {
  60625. manifestChecked();
  60626. }
  60627. }
  60628. else {
  60629. var fileOrString = sceneFilename;
  60630. if (fileOrString.name) {
  60631. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  60632. }
  60633. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  60634. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  60635. }
  60636. else {
  60637. onError("Unable to find file named " + sceneFilename);
  60638. }
  60639. }
  60640. return plugin;
  60641. };
  60642. // Public functions
  60643. SceneLoader.GetPluginForExtension = function (extension) {
  60644. return SceneLoader._getPluginForExtension(extension).plugin;
  60645. };
  60646. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  60647. return !!SceneLoader._registeredPlugins[extension];
  60648. };
  60649. SceneLoader.RegisterPlugin = function (plugin) {
  60650. if (typeof plugin.extensions === "string") {
  60651. var extension = plugin.extensions;
  60652. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60653. plugin: plugin,
  60654. isBinary: false
  60655. };
  60656. }
  60657. else {
  60658. var extensions = plugin.extensions;
  60659. Object.keys(extensions).forEach(function (extension) {
  60660. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60661. plugin: plugin,
  60662. isBinary: extensions[extension].isBinary
  60663. };
  60664. });
  60665. }
  60666. };
  60667. /**
  60668. * Import meshes into a scene
  60669. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60670. * @param rootUrl a string that defines the root url for scene and resources
  60671. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60672. * @param scene the instance of BABYLON.Scene to append to
  60673. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  60674. * @param onProgress a callback with a progress event for each file being loaded
  60675. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60676. * @param pluginExtension the extension used to determine the plugin
  60677. * @returns The loaded plugin
  60678. */
  60679. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60680. if (onSuccess === void 0) { onSuccess = null; }
  60681. if (onProgress === void 0) { onProgress = null; }
  60682. if (onError === void 0) { onError = null; }
  60683. if (pluginExtension === void 0) { pluginExtension = null; }
  60684. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60685. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60686. return null;
  60687. }
  60688. var loadingToken = {};
  60689. scene._addPendingData(loadingToken);
  60690. var disposeHandler = function () {
  60691. scene._removePendingData(loadingToken);
  60692. };
  60693. var errorHandler = function (message, exception) {
  60694. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  60695. if (onError) {
  60696. onError(scene, errorMessage, exception);
  60697. }
  60698. else {
  60699. BABYLON.Tools.Error(errorMessage);
  60700. // should the exception be thrown?
  60701. }
  60702. disposeHandler();
  60703. };
  60704. var progressHandler = onProgress ? function (event) {
  60705. try {
  60706. onProgress(event);
  60707. }
  60708. catch (e) {
  60709. errorHandler("Error in onProgress callback", e);
  60710. }
  60711. } : undefined;
  60712. var successHandler = function (meshes, particleSystems, skeletons) {
  60713. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  60714. if (onSuccess) {
  60715. try {
  60716. onSuccess(meshes, particleSystems, skeletons);
  60717. }
  60718. catch (e) {
  60719. errorHandler("Error in onSuccess callback", e);
  60720. }
  60721. }
  60722. scene._removePendingData(loadingToken);
  60723. };
  60724. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60725. if (plugin.rewriteRootURL) {
  60726. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  60727. }
  60728. if (sceneFilename === "") {
  60729. if (sceneFilename === "") {
  60730. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60731. }
  60732. }
  60733. if (plugin.importMesh) {
  60734. var syncedPlugin = plugin;
  60735. var meshes = new Array();
  60736. var particleSystems = new Array();
  60737. var skeletons = new Array();
  60738. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  60739. return;
  60740. }
  60741. scene.loadingPluginName = plugin.name;
  60742. successHandler(meshes, particleSystems, skeletons);
  60743. }
  60744. else {
  60745. var asyncedPlugin = plugin;
  60746. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  60747. scene.loadingPluginName = plugin.name;
  60748. successHandler(result.meshes, result.particleSystems, result.skeletons);
  60749. }).catch(function (error) {
  60750. errorHandler(error.message, error);
  60751. });
  60752. }
  60753. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60754. };
  60755. /**
  60756. * Import meshes into a scene
  60757. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60758. * @param rootUrl a string that defines the root url for scene and resources
  60759. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60760. * @param scene the instance of BABYLON.Scene to append to
  60761. * @param onProgress a callback with a progress event for each file being loaded
  60762. * @param pluginExtension the extension used to determine the plugin
  60763. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  60764. */
  60765. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60766. if (onProgress === void 0) { onProgress = null; }
  60767. if (pluginExtension === void 0) { pluginExtension = null; }
  60768. return new Promise(function (resolve, reject) {
  60769. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  60770. resolve({
  60771. meshes: meshes,
  60772. particleSystems: particleSystems,
  60773. skeletons: skeletons
  60774. });
  60775. }, onProgress, function (scene, message, exception) {
  60776. reject(exception || new Error(message));
  60777. });
  60778. });
  60779. };
  60780. /**
  60781. * Load a scene
  60782. * @param rootUrl a string that defines the root url for scene and resources
  60783. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60784. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60785. * @param onSuccess a callback with the scene when import succeeds
  60786. * @param onProgress a callback with a progress event for each file being loaded
  60787. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60788. * @param pluginExtension the extension used to determine the plugin
  60789. * @returns The loaded plugin
  60790. */
  60791. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  60792. if (onSuccess === void 0) { onSuccess = null; }
  60793. if (onProgress === void 0) { onProgress = null; }
  60794. if (onError === void 0) { onError = null; }
  60795. if (pluginExtension === void 0) { pluginExtension = null; }
  60796. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  60797. };
  60798. /**
  60799. * Load a scene
  60800. * @param rootUrl a string that defines the root url for scene and resources
  60801. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60802. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60803. * @param onProgress a callback with a progress event for each file being loaded
  60804. * @param pluginExtension the extension used to determine the plugin
  60805. * @returns The loaded scene
  60806. */
  60807. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  60808. if (onProgress === void 0) { onProgress = null; }
  60809. if (pluginExtension === void 0) { pluginExtension = null; }
  60810. return new Promise(function (resolve, reject) {
  60811. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  60812. resolve(scene);
  60813. }, onProgress, function (scene, message, exception) {
  60814. reject(exception || new Error(message));
  60815. }, pluginExtension);
  60816. });
  60817. };
  60818. /**
  60819. * Append a scene
  60820. * @param rootUrl a string that defines the root url for scene and resources
  60821. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60822. * @param scene is the instance of BABYLON.Scene to append to
  60823. * @param onSuccess a callback with the scene when import succeeds
  60824. * @param onProgress a callback with a progress event for each file being loaded
  60825. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60826. * @param pluginExtension the extension used to determine the plugin
  60827. * @returns The loaded plugin
  60828. */
  60829. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60830. if (onSuccess === void 0) { onSuccess = null; }
  60831. if (onProgress === void 0) { onProgress = null; }
  60832. if (onError === void 0) { onError = null; }
  60833. if (pluginExtension === void 0) { pluginExtension = null; }
  60834. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60835. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60836. return null;
  60837. }
  60838. if (SceneLoader.ShowLoadingScreen) {
  60839. scene.getEngine().displayLoadingUI();
  60840. }
  60841. var loadingToken = {};
  60842. scene._addPendingData(loadingToken);
  60843. var disposeHandler = function () {
  60844. scene._removePendingData(loadingToken);
  60845. scene.getEngine().hideLoadingUI();
  60846. };
  60847. var errorHandler = function (message, exception) {
  60848. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60849. if (onError) {
  60850. onError(scene, errorMessage, exception);
  60851. }
  60852. else {
  60853. BABYLON.Tools.Error(errorMessage);
  60854. // should the exception be thrown?
  60855. }
  60856. disposeHandler();
  60857. };
  60858. var progressHandler = onProgress ? function (event) {
  60859. try {
  60860. onProgress(event);
  60861. }
  60862. catch (e) {
  60863. errorHandler("Error in onProgress callback", e);
  60864. }
  60865. } : undefined;
  60866. var successHandler = function () {
  60867. if (onSuccess) {
  60868. try {
  60869. onSuccess(scene);
  60870. }
  60871. catch (e) {
  60872. errorHandler("Error in onSuccess callback", e);
  60873. }
  60874. }
  60875. scene._removePendingData(loadingToken);
  60876. };
  60877. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60878. if (sceneFilename === "") {
  60879. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60880. }
  60881. if (plugin.load) {
  60882. var syncedPlugin = plugin;
  60883. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  60884. return;
  60885. }
  60886. scene.loadingPluginName = plugin.name;
  60887. successHandler();
  60888. }
  60889. else {
  60890. var asyncedPlugin = plugin;
  60891. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  60892. scene.loadingPluginName = plugin.name;
  60893. successHandler();
  60894. }).catch(function (error) {
  60895. errorHandler(error.message, error);
  60896. });
  60897. }
  60898. if (SceneLoader.ShowLoadingScreen) {
  60899. scene.executeWhenReady(function () {
  60900. scene.getEngine().hideLoadingUI();
  60901. });
  60902. }
  60903. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60904. };
  60905. /**
  60906. * Append a scene
  60907. * @param rootUrl a string that defines the root url for scene and resources
  60908. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60909. * @param scene is the instance of BABYLON.Scene to append to
  60910. * @param onProgress a callback with a progress event for each file being loaded
  60911. * @param pluginExtension the extension used to determine the plugin
  60912. * @returns The given scene
  60913. */
  60914. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60915. if (onProgress === void 0) { onProgress = null; }
  60916. if (pluginExtension === void 0) { pluginExtension = null; }
  60917. return new Promise(function (resolve, reject) {
  60918. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  60919. resolve(scene);
  60920. }, onProgress, function (scene, message, exception) {
  60921. reject(exception || new Error(message));
  60922. }, pluginExtension);
  60923. });
  60924. };
  60925. /**
  60926. * Load a scene into an asset container
  60927. * @param rootUrl a string that defines the root url for scene and resources
  60928. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60929. * @param scene is the instance of BABYLON.Scene to append to
  60930. * @param onSuccess a callback with the scene when import succeeds
  60931. * @param onProgress a callback with a progress event for each file being loaded
  60932. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60933. * @param pluginExtension the extension used to determine the plugin
  60934. * @returns The loaded plugin
  60935. */
  60936. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60937. if (onSuccess === void 0) { onSuccess = null; }
  60938. if (onProgress === void 0) { onProgress = null; }
  60939. if (onError === void 0) { onError = null; }
  60940. if (pluginExtension === void 0) { pluginExtension = null; }
  60941. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60942. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60943. return null;
  60944. }
  60945. var loadingToken = {};
  60946. scene._addPendingData(loadingToken);
  60947. var disposeHandler = function () {
  60948. scene._removePendingData(loadingToken);
  60949. };
  60950. var errorHandler = function (message, exception) {
  60951. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60952. if (onError) {
  60953. onError(scene, errorMessage, exception);
  60954. }
  60955. else {
  60956. BABYLON.Tools.Error(errorMessage);
  60957. // should the exception be thrown?
  60958. }
  60959. disposeHandler();
  60960. };
  60961. var progressHandler = onProgress ? function (event) {
  60962. try {
  60963. onProgress(event);
  60964. }
  60965. catch (e) {
  60966. errorHandler("Error in onProgress callback", e);
  60967. }
  60968. } : undefined;
  60969. var successHandler = function (assets) {
  60970. if (onSuccess) {
  60971. try {
  60972. onSuccess(assets);
  60973. }
  60974. catch (e) {
  60975. errorHandler("Error in onSuccess callback", e);
  60976. }
  60977. }
  60978. scene._removePendingData(loadingToken);
  60979. };
  60980. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60981. if (plugin.loadAssetContainer) {
  60982. var syncedPlugin = plugin;
  60983. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  60984. if (!assetContainer) {
  60985. return;
  60986. }
  60987. scene.loadingPluginName = plugin.name;
  60988. successHandler(assetContainer);
  60989. }
  60990. else if (plugin.loadAssetContainerAsync) {
  60991. var asyncedPlugin = plugin;
  60992. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  60993. scene.loadingPluginName = plugin.name;
  60994. successHandler(assetContainer);
  60995. }).catch(function (error) {
  60996. errorHandler(error.message, error);
  60997. });
  60998. }
  60999. else {
  61000. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  61001. }
  61002. if (SceneLoader.ShowLoadingScreen) {
  61003. scene.executeWhenReady(function () {
  61004. scene.getEngine().hideLoadingUI();
  61005. });
  61006. }
  61007. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61008. };
  61009. /**
  61010. * Load a scene into an asset container
  61011. * @param rootUrl a string that defines the root url for scene and resources
  61012. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61013. * @param scene is the instance of BABYLON.Scene to append to
  61014. * @param onProgress a callback with a progress event for each file being loaded
  61015. * @param pluginExtension the extension used to determine the plugin
  61016. * @returns The loaded asset container
  61017. */
  61018. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61019. if (onProgress === void 0) { onProgress = null; }
  61020. if (pluginExtension === void 0) { pluginExtension = null; }
  61021. return new Promise(function (resolve, reject) {
  61022. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  61023. resolve(assetContainer);
  61024. }, onProgress, function (scene, message, exception) {
  61025. reject(exception || new Error(message));
  61026. }, pluginExtension);
  61027. });
  61028. };
  61029. // Flags
  61030. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  61031. SceneLoader._ShowLoadingScreen = true;
  61032. SceneLoader._CleanBoneMatrixWeights = false;
  61033. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  61034. // Members
  61035. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  61036. SceneLoader._registeredPlugins = {};
  61037. return SceneLoader;
  61038. }());
  61039. BABYLON.SceneLoader = SceneLoader;
  61040. ;
  61041. })(BABYLON || (BABYLON = {}));
  61042. //# sourceMappingURL=babylon.sceneLoader.js.map
  61043. var BABYLON;
  61044. (function (BABYLON) {
  61045. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  61046. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61047. var parsedMaterial = parsedData.materials[index];
  61048. if (parsedMaterial.id === id) {
  61049. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61050. }
  61051. }
  61052. return null;
  61053. };
  61054. var isDescendantOf = function (mesh, names, hierarchyIds) {
  61055. for (var i in names) {
  61056. if (mesh.name === names[i]) {
  61057. hierarchyIds.push(mesh.id);
  61058. return true;
  61059. }
  61060. }
  61061. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  61062. hierarchyIds.push(mesh.id);
  61063. return true;
  61064. }
  61065. return false;
  61066. };
  61067. var logOperation = function (operation, producer) {
  61068. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  61069. };
  61070. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  61071. if (addToScene === void 0) { addToScene = false; }
  61072. var container = new BABYLON.AssetContainer(scene);
  61073. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61074. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61075. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61076. // and avoid problems with multiple concurrent .babylon loads.
  61077. var log = "importScene has failed JSON parse";
  61078. try {
  61079. var parsedData = JSON.parse(data);
  61080. log = "";
  61081. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61082. var index;
  61083. var cache;
  61084. // Lights
  61085. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  61086. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  61087. var parsedLight = parsedData.lights[index];
  61088. var light = BABYLON.Light.Parse(parsedLight, scene);
  61089. if (light) {
  61090. container.lights.push(light);
  61091. log += (index === 0 ? "\n\tLights:" : "");
  61092. log += "\n\t\t" + light.toString(fullDetails);
  61093. }
  61094. }
  61095. }
  61096. // Animations
  61097. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61098. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61099. var parsedAnimation = parsedData.animations[index];
  61100. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61101. scene.animations.push(animation);
  61102. container.animations.push(animation);
  61103. log += (index === 0 ? "\n\tAnimations:" : "");
  61104. log += "\n\t\t" + animation.toString(fullDetails);
  61105. }
  61106. }
  61107. // Materials
  61108. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  61109. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61110. var parsedMaterial = parsedData.materials[index];
  61111. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61112. container.materials.push(mat);
  61113. log += (index === 0 ? "\n\tMaterials:" : "");
  61114. log += "\n\t\t" + mat.toString(fullDetails);
  61115. }
  61116. }
  61117. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61118. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  61119. var parsedMultiMaterial = parsedData.multiMaterials[index];
  61120. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61121. container.multiMaterials.push(mmat);
  61122. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  61123. log += "\n\t\t" + mmat.toString(fullDetails);
  61124. }
  61125. }
  61126. // Morph targets
  61127. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  61128. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  61129. var managerData = _a[_i];
  61130. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  61131. }
  61132. }
  61133. // Skeletons
  61134. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61135. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  61136. var parsedSkeleton = parsedData.skeletons[index];
  61137. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61138. container.skeletons.push(skeleton);
  61139. log += (index === 0 ? "\n\tSkeletons:" : "");
  61140. log += "\n\t\t" + skeleton.toString(fullDetails);
  61141. }
  61142. }
  61143. // Geometries
  61144. var geometries = parsedData.geometries;
  61145. if (geometries !== undefined && geometries !== null) {
  61146. var addedGeometry = new Array();
  61147. // Boxes
  61148. var boxes = geometries.boxes;
  61149. if (boxes !== undefined && boxes !== null) {
  61150. for (index = 0, cache = boxes.length; index < cache; index++) {
  61151. var parsedBox = boxes[index];
  61152. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  61153. }
  61154. }
  61155. // Spheres
  61156. var spheres = geometries.spheres;
  61157. if (spheres !== undefined && spheres !== null) {
  61158. for (index = 0, cache = spheres.length; index < cache; index++) {
  61159. var parsedSphere = spheres[index];
  61160. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  61161. }
  61162. }
  61163. // Cylinders
  61164. var cylinders = geometries.cylinders;
  61165. if (cylinders !== undefined && cylinders !== null) {
  61166. for (index = 0, cache = cylinders.length; index < cache; index++) {
  61167. var parsedCylinder = cylinders[index];
  61168. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  61169. }
  61170. }
  61171. // Toruses
  61172. var toruses = geometries.toruses;
  61173. if (toruses !== undefined && toruses !== null) {
  61174. for (index = 0, cache = toruses.length; index < cache; index++) {
  61175. var parsedTorus = toruses[index];
  61176. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  61177. }
  61178. }
  61179. // Grounds
  61180. var grounds = geometries.grounds;
  61181. if (grounds !== undefined && grounds !== null) {
  61182. for (index = 0, cache = grounds.length; index < cache; index++) {
  61183. var parsedGround = grounds[index];
  61184. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  61185. }
  61186. }
  61187. // Planes
  61188. var planes = geometries.planes;
  61189. if (planes !== undefined && planes !== null) {
  61190. for (index = 0, cache = planes.length; index < cache; index++) {
  61191. var parsedPlane = planes[index];
  61192. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  61193. }
  61194. }
  61195. // TorusKnots
  61196. var torusKnots = geometries.torusKnots;
  61197. if (torusKnots !== undefined && torusKnots !== null) {
  61198. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  61199. var parsedTorusKnot = torusKnots[index];
  61200. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  61201. }
  61202. }
  61203. // VertexData
  61204. var vertexData = geometries.vertexData;
  61205. if (vertexData !== undefined && vertexData !== null) {
  61206. for (index = 0, cache = vertexData.length; index < cache; index++) {
  61207. var parsedVertexData = vertexData[index];
  61208. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  61209. }
  61210. }
  61211. addedGeometry.forEach(function (g) {
  61212. if (g) {
  61213. container.geometries.push(g);
  61214. }
  61215. });
  61216. }
  61217. // Transform nodes
  61218. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  61219. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  61220. var parsedTransformNode = parsedData.transformNodes[index];
  61221. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  61222. container.transformNodes.push(node);
  61223. }
  61224. }
  61225. // Meshes
  61226. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61227. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61228. var parsedMesh = parsedData.meshes[index];
  61229. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61230. container.meshes.push(mesh);
  61231. log += (index === 0 ? "\n\tMeshes:" : "");
  61232. log += "\n\t\t" + mesh.toString(fullDetails);
  61233. }
  61234. }
  61235. // Cameras
  61236. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  61237. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61238. var parsedCamera = parsedData.cameras[index];
  61239. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61240. container.cameras.push(camera);
  61241. log += (index === 0 ? "\n\tCameras:" : "");
  61242. log += "\n\t\t" + camera.toString(fullDetails);
  61243. }
  61244. }
  61245. // Browsing all the graph to connect the dots
  61246. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61247. var camera = scene.cameras[index];
  61248. if (camera._waitingParentId) {
  61249. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61250. camera._waitingParentId = null;
  61251. }
  61252. }
  61253. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61254. var light_1 = scene.lights[index];
  61255. if (light_1 && light_1._waitingParentId) {
  61256. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61257. light_1._waitingParentId = null;
  61258. }
  61259. }
  61260. // Sounds
  61261. // TODO: add sound
  61262. var loadedSounds = [];
  61263. var loadedSound;
  61264. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61265. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61266. var parsedSound = parsedData.sounds[index];
  61267. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61268. if (!parsedSound.url)
  61269. parsedSound.url = parsedSound.name;
  61270. if (!loadedSounds[parsedSound.url]) {
  61271. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  61272. loadedSounds[parsedSound.url] = loadedSound;
  61273. container.sounds.push(loadedSound);
  61274. }
  61275. else {
  61276. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  61277. }
  61278. }
  61279. else {
  61280. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  61281. }
  61282. }
  61283. }
  61284. loadedSounds = [];
  61285. // Connect parents & children and parse actions
  61286. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  61287. var transformNode = scene.transformNodes[index];
  61288. if (transformNode._waitingParentId) {
  61289. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  61290. transformNode._waitingParentId = null;
  61291. }
  61292. }
  61293. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61294. var mesh = scene.meshes[index];
  61295. if (mesh._waitingParentId) {
  61296. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  61297. mesh._waitingParentId = null;
  61298. }
  61299. if (mesh._waitingActions) {
  61300. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  61301. mesh._waitingActions = null;
  61302. }
  61303. }
  61304. // freeze world matrix application
  61305. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61306. var currentMesh = scene.meshes[index];
  61307. if (currentMesh._waitingFreezeWorldMatrix) {
  61308. currentMesh.freezeWorldMatrix();
  61309. currentMesh._waitingFreezeWorldMatrix = null;
  61310. }
  61311. else {
  61312. currentMesh.computeWorldMatrix(true);
  61313. }
  61314. }
  61315. // Particles Systems
  61316. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61317. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61318. var parsedParticleSystem = parsedData.particleSystems[index];
  61319. if (parsedParticleSystem.activeParticleCount) {
  61320. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61321. container.particleSystems.push(ps);
  61322. }
  61323. else {
  61324. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61325. container.particleSystems.push(ps);
  61326. }
  61327. }
  61328. }
  61329. // Lens flares
  61330. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  61331. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  61332. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  61333. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  61334. container.lensFlareSystems.push(lf);
  61335. }
  61336. }
  61337. // Shadows
  61338. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  61339. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  61340. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  61341. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  61342. container.shadowGenerators.push(sg);
  61343. }
  61344. }
  61345. // Lights exclusions / inclusions
  61346. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61347. var light_2 = scene.lights[index];
  61348. // Excluded check
  61349. if (light_2._excludedMeshesIds.length > 0) {
  61350. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  61351. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  61352. if (excludedMesh) {
  61353. light_2.excludedMeshes.push(excludedMesh);
  61354. }
  61355. }
  61356. light_2._excludedMeshesIds = [];
  61357. }
  61358. // Included check
  61359. if (light_2._includedOnlyMeshesIds.length > 0) {
  61360. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  61361. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  61362. if (includedOnlyMesh) {
  61363. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  61364. }
  61365. }
  61366. light_2._includedOnlyMeshesIds = [];
  61367. }
  61368. }
  61369. // Actions (scene)
  61370. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  61371. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  61372. }
  61373. if (!addToScene) {
  61374. container.removeAllFromScene();
  61375. }
  61376. }
  61377. catch (err) {
  61378. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  61379. if (onError) {
  61380. onError(msg, err);
  61381. }
  61382. else {
  61383. BABYLON.Tools.Log(msg);
  61384. throw err;
  61385. }
  61386. }
  61387. finally {
  61388. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61389. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61390. }
  61391. }
  61392. return container;
  61393. };
  61394. BABYLON.SceneLoader.RegisterPlugin({
  61395. name: "babylon.js",
  61396. extensions: ".babylon",
  61397. canDirectLoad: function (data) {
  61398. if (data.indexOf("babylon") !== -1) {
  61399. return true;
  61400. }
  61401. return false;
  61402. },
  61403. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  61404. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61405. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61406. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61407. // and avoid problems with multiple concurrent .babylon loads.
  61408. var log = "importMesh has failed JSON parse";
  61409. try {
  61410. var parsedData = JSON.parse(data);
  61411. log = "";
  61412. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61413. if (!meshesNames) {
  61414. meshesNames = null;
  61415. }
  61416. else if (!Array.isArray(meshesNames)) {
  61417. meshesNames = [meshesNames];
  61418. }
  61419. var hierarchyIds = new Array();
  61420. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61421. var loadedSkeletonsIds = [];
  61422. var loadedMaterialsIds = [];
  61423. var index;
  61424. var cache;
  61425. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61426. var parsedMesh = parsedData.meshes[index];
  61427. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  61428. if (meshesNames !== null) {
  61429. // Remove found mesh name from list.
  61430. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  61431. }
  61432. //Geometry?
  61433. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  61434. //does the file contain geometries?
  61435. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  61436. //find the correct geometry and add it to the scene
  61437. var found = false;
  61438. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  61439. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  61440. return;
  61441. }
  61442. else {
  61443. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  61444. if (parsedGeometryData.id === parsedMesh.geometryId) {
  61445. switch (geometryType) {
  61446. case "boxes":
  61447. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  61448. break;
  61449. case "spheres":
  61450. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  61451. break;
  61452. case "cylinders":
  61453. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  61454. break;
  61455. case "toruses":
  61456. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  61457. break;
  61458. case "grounds":
  61459. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  61460. break;
  61461. case "planes":
  61462. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  61463. break;
  61464. case "torusKnots":
  61465. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  61466. break;
  61467. case "vertexData":
  61468. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  61469. break;
  61470. }
  61471. found = true;
  61472. }
  61473. });
  61474. }
  61475. });
  61476. if (found === false) {
  61477. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  61478. }
  61479. }
  61480. }
  61481. // Material ?
  61482. if (parsedMesh.materialId) {
  61483. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  61484. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61485. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  61486. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  61487. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  61488. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  61489. var subMatId = parsedMultiMaterial.materials[matIndex];
  61490. loadedMaterialsIds.push(subMatId);
  61491. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  61492. if (mat) {
  61493. log += "\n\tMaterial " + mat.toString(fullDetails);
  61494. }
  61495. }
  61496. loadedMaterialsIds.push(parsedMultiMaterial.id);
  61497. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61498. if (mmat) {
  61499. materialFound = true;
  61500. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  61501. }
  61502. break;
  61503. }
  61504. }
  61505. }
  61506. if (materialFound === false) {
  61507. loadedMaterialsIds.push(parsedMesh.materialId);
  61508. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  61509. if (!mat) {
  61510. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  61511. }
  61512. else {
  61513. log += "\n\tMaterial " + mat.toString(fullDetails);
  61514. }
  61515. }
  61516. }
  61517. // Skeleton ?
  61518. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61519. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  61520. if (skeletonAlreadyLoaded === false) {
  61521. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  61522. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  61523. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  61524. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61525. skeletons.push(skeleton);
  61526. loadedSkeletonsIds.push(parsedSkeleton.id);
  61527. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  61528. }
  61529. }
  61530. }
  61531. }
  61532. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61533. meshes.push(mesh);
  61534. log += "\n\tMesh " + mesh.toString(fullDetails);
  61535. }
  61536. }
  61537. // Connecting parents
  61538. var currentMesh;
  61539. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61540. currentMesh = scene.meshes[index];
  61541. if (currentMesh._waitingParentId) {
  61542. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  61543. currentMesh._waitingParentId = null;
  61544. }
  61545. }
  61546. // freeze and compute world matrix application
  61547. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61548. currentMesh = scene.meshes[index];
  61549. if (currentMesh._waitingFreezeWorldMatrix) {
  61550. currentMesh.freezeWorldMatrix();
  61551. currentMesh._waitingFreezeWorldMatrix = null;
  61552. }
  61553. else {
  61554. currentMesh.computeWorldMatrix(true);
  61555. }
  61556. }
  61557. }
  61558. // Particles
  61559. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61560. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61561. var parsedParticleSystem = parsedData.particleSystems[index];
  61562. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  61563. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  61564. }
  61565. }
  61566. }
  61567. return true;
  61568. }
  61569. catch (err) {
  61570. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  61571. if (onError) {
  61572. onError(msg, err);
  61573. }
  61574. else {
  61575. BABYLON.Tools.Log(msg);
  61576. throw err;
  61577. }
  61578. }
  61579. finally {
  61580. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61581. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61582. }
  61583. }
  61584. return false;
  61585. },
  61586. load: function (scene, data, rootUrl, onError) {
  61587. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61588. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61589. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61590. // and avoid problems with multiple concurrent .babylon loads.
  61591. var log = "importScene has failed JSON parse";
  61592. try {
  61593. var parsedData = JSON.parse(data);
  61594. log = "";
  61595. // Scene
  61596. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  61597. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  61598. }
  61599. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  61600. scene.autoClear = parsedData.autoClear;
  61601. }
  61602. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  61603. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  61604. }
  61605. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  61606. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  61607. }
  61608. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  61609. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  61610. }
  61611. // Fog
  61612. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  61613. scene.fogMode = parsedData.fogMode;
  61614. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  61615. scene.fogStart = parsedData.fogStart;
  61616. scene.fogEnd = parsedData.fogEnd;
  61617. scene.fogDensity = parsedData.fogDensity;
  61618. log += "\tFog mode for scene: ";
  61619. switch (scene.fogMode) {
  61620. // getters not compiling, so using hardcoded
  61621. case 1:
  61622. log += "exp\n";
  61623. break;
  61624. case 2:
  61625. log += "exp2\n";
  61626. break;
  61627. case 3:
  61628. log += "linear\n";
  61629. break;
  61630. }
  61631. }
  61632. //Physics
  61633. if (parsedData.physicsEnabled) {
  61634. var physicsPlugin;
  61635. if (parsedData.physicsEngine === "cannon") {
  61636. physicsPlugin = new BABYLON.CannonJSPlugin();
  61637. }
  61638. else if (parsedData.physicsEngine === "oimo") {
  61639. physicsPlugin = new BABYLON.OimoJSPlugin();
  61640. }
  61641. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  61642. //else - default engine, which is currently oimo
  61643. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  61644. scene.enablePhysics(physicsGravity, physicsPlugin);
  61645. }
  61646. // Metadata
  61647. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  61648. scene.metadata = parsedData.metadata;
  61649. }
  61650. //collisions, if defined. otherwise, default is true
  61651. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  61652. scene.collisionsEnabled = parsedData.collisionsEnabled;
  61653. }
  61654. scene.workerCollisions = !!parsedData.workerCollisions;
  61655. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  61656. if (!container) {
  61657. return false;
  61658. }
  61659. if (parsedData.autoAnimate) {
  61660. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  61661. }
  61662. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  61663. scene.setActiveCameraByID(parsedData.activeCameraID);
  61664. }
  61665. // Environment texture
  61666. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  61667. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  61668. if (parsedData.createDefaultSkybox === true) {
  61669. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  61670. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  61671. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  61672. }
  61673. }
  61674. // Finish
  61675. return true;
  61676. }
  61677. catch (err) {
  61678. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  61679. if (onError) {
  61680. onError(msg, err);
  61681. }
  61682. else {
  61683. BABYLON.Tools.Log(msg);
  61684. throw err;
  61685. }
  61686. }
  61687. finally {
  61688. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61689. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61690. }
  61691. }
  61692. return false;
  61693. },
  61694. loadAssetContainer: function (scene, data, rootUrl, onError) {
  61695. var container = loadAssetContainer(scene, data, rootUrl, onError);
  61696. return container;
  61697. }
  61698. });
  61699. })(BABYLON || (BABYLON = {}));
  61700. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  61701. var BABYLON;
  61702. (function (BABYLON) {
  61703. var FilesInput = /** @class */ (function () {
  61704. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  61705. this.onProcessFileCallback = function () { return true; };
  61706. this._engine = engine;
  61707. this._currentScene = scene;
  61708. this._sceneLoadedCallback = sceneLoadedCallback;
  61709. this._progressCallback = progressCallback;
  61710. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  61711. this._textureLoadingCallback = textureLoadingCallback;
  61712. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  61713. this._onReloadCallback = onReloadCallback;
  61714. this._errorCallback = errorCallback;
  61715. }
  61716. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  61717. var _this = this;
  61718. if (elementToMonitor) {
  61719. this._elementToMonitor = elementToMonitor;
  61720. this._dragEnterHandler = function (e) { _this.drag(e); };
  61721. this._dragOverHandler = function (e) { _this.drag(e); };
  61722. this._dropHandler = function (e) { _this.drop(e); };
  61723. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  61724. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  61725. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  61726. }
  61727. };
  61728. FilesInput.prototype.dispose = function () {
  61729. if (!this._elementToMonitor) {
  61730. return;
  61731. }
  61732. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  61733. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  61734. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  61735. };
  61736. FilesInput.prototype.renderFunction = function () {
  61737. if (this._additionalRenderLoopLogicCallback) {
  61738. this._additionalRenderLoopLogicCallback();
  61739. }
  61740. if (this._currentScene) {
  61741. if (this._textureLoadingCallback) {
  61742. var remaining = this._currentScene.getWaitingItemsCount();
  61743. if (remaining > 0) {
  61744. this._textureLoadingCallback(remaining);
  61745. }
  61746. }
  61747. this._currentScene.render();
  61748. }
  61749. };
  61750. FilesInput.prototype.drag = function (e) {
  61751. e.stopPropagation();
  61752. e.preventDefault();
  61753. };
  61754. FilesInput.prototype.drop = function (eventDrop) {
  61755. eventDrop.stopPropagation();
  61756. eventDrop.preventDefault();
  61757. this.loadFiles(eventDrop);
  61758. };
  61759. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  61760. var _this = this;
  61761. var reader = folder.createReader();
  61762. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  61763. reader.readEntries(function (entries) {
  61764. remaining.count += entries.length;
  61765. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  61766. var entry = entries_1[_i];
  61767. if (entry.isFile) {
  61768. entry.file(function (file) {
  61769. file.correctName = relativePath + file.name;
  61770. files.push(file);
  61771. if (--remaining.count === 0) {
  61772. callback();
  61773. }
  61774. });
  61775. }
  61776. else if (entry.isDirectory) {
  61777. _this._traverseFolder(entry, files, remaining, callback);
  61778. }
  61779. }
  61780. if (--remaining.count) {
  61781. callback();
  61782. }
  61783. });
  61784. };
  61785. FilesInput.prototype._processFiles = function (files) {
  61786. for (var i = 0; i < files.length; i++) {
  61787. var name = files[i].correctName.toLowerCase();
  61788. var extension = name.split('.').pop();
  61789. if (!this.onProcessFileCallback(files[i], name, extension)) {
  61790. continue;
  61791. }
  61792. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  61793. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  61794. this._sceneFileToLoad = files[i];
  61795. }
  61796. else {
  61797. FilesInput.FilesToLoad[name] = files[i];
  61798. }
  61799. }
  61800. };
  61801. FilesInput.prototype.loadFiles = function (event) {
  61802. var _this = this;
  61803. if (this._startingProcessingFilesCallback)
  61804. this._startingProcessingFilesCallback();
  61805. // Handling data transfer via drag'n'drop
  61806. if (event && event.dataTransfer && event.dataTransfer.files) {
  61807. this._filesToLoad = event.dataTransfer.files;
  61808. }
  61809. // Handling files from input files
  61810. if (event && event.target && event.target.files) {
  61811. this._filesToLoad = event.target.files;
  61812. }
  61813. if (this._filesToLoad && this._filesToLoad.length > 0) {
  61814. var files_1 = new Array();
  61815. var folders = [];
  61816. var items = event.dataTransfer ? event.dataTransfer.items : null;
  61817. for (var i = 0; i < this._filesToLoad.length; i++) {
  61818. var fileToLoad = this._filesToLoad[i];
  61819. var name_1 = fileToLoad.name.toLowerCase();
  61820. var entry = void 0;
  61821. fileToLoad.correctName = name_1;
  61822. if (items) {
  61823. var item = items[i];
  61824. if (item.getAsEntry) {
  61825. entry = item.getAsEntry();
  61826. }
  61827. else if (item.webkitGetAsEntry) {
  61828. entry = item.webkitGetAsEntry();
  61829. }
  61830. }
  61831. if (!entry) {
  61832. files_1.push(fileToLoad);
  61833. }
  61834. else {
  61835. if (entry.isDirectory) {
  61836. folders.push(entry);
  61837. }
  61838. else {
  61839. files_1.push(fileToLoad);
  61840. }
  61841. }
  61842. }
  61843. if (folders.length === 0) {
  61844. this._processFiles(files_1);
  61845. this._processReload();
  61846. }
  61847. else {
  61848. var remaining = { count: folders.length };
  61849. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  61850. var folder = folders_1[_i];
  61851. this._traverseFolder(folder, files_1, remaining, function () {
  61852. _this._processFiles(files_1);
  61853. if (remaining.count === 0) {
  61854. _this._processReload();
  61855. }
  61856. });
  61857. }
  61858. }
  61859. }
  61860. };
  61861. FilesInput.prototype._processReload = function () {
  61862. if (this._onReloadCallback) {
  61863. this._onReloadCallback(this._sceneFileToLoad);
  61864. }
  61865. else {
  61866. this.reload();
  61867. }
  61868. };
  61869. FilesInput.prototype.reload = function () {
  61870. var _this = this;
  61871. // If a scene file has been provided
  61872. if (this._sceneFileToLoad) {
  61873. if (this._currentScene) {
  61874. if (BABYLON.Tools.errorsCount > 0) {
  61875. BABYLON.Tools.ClearLogCache();
  61876. }
  61877. this._engine.stopRenderLoop();
  61878. this._currentScene.dispose();
  61879. }
  61880. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  61881. if (_this._progressCallback) {
  61882. _this._progressCallback(progress);
  61883. }
  61884. }).then(function (scene) {
  61885. _this._currentScene = scene;
  61886. if (_this._sceneLoadedCallback) {
  61887. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  61888. }
  61889. // Wait for textures and shaders to be ready
  61890. _this._currentScene.executeWhenReady(function () {
  61891. _this._engine.runRenderLoop(function () {
  61892. _this.renderFunction();
  61893. });
  61894. });
  61895. }).catch(function (error) {
  61896. if (_this._errorCallback) {
  61897. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  61898. }
  61899. });
  61900. }
  61901. else {
  61902. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  61903. }
  61904. };
  61905. FilesInput.FilesToLoad = {};
  61906. return FilesInput;
  61907. }());
  61908. BABYLON.FilesInput = FilesInput;
  61909. })(BABYLON || (BABYLON = {}));
  61910. //# sourceMappingURL=babylon.filesInput.js.map
  61911. var BABYLON;
  61912. (function (BABYLON) {
  61913. /**
  61914. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61915. * The underlying implementation relies on an associative array to ensure the best performances.
  61916. * The value can be anything including 'null' but except 'undefined'
  61917. */
  61918. var StringDictionary = /** @class */ (function () {
  61919. function StringDictionary() {
  61920. this._count = 0;
  61921. this._data = {};
  61922. }
  61923. /**
  61924. * This will clear this dictionary and copy the content from the 'source' one.
  61925. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61926. * @param source the dictionary to take the content from and copy to this dictionary
  61927. */
  61928. StringDictionary.prototype.copyFrom = function (source) {
  61929. var _this = this;
  61930. this.clear();
  61931. source.forEach(function (t, v) { return _this.add(t, v); });
  61932. };
  61933. /**
  61934. * Get a value based from its key
  61935. * @param key the given key to get the matching value from
  61936. * @return the value if found, otherwise undefined is returned
  61937. */
  61938. StringDictionary.prototype.get = function (key) {
  61939. var val = this._data[key];
  61940. if (val !== undefined) {
  61941. return val;
  61942. }
  61943. return undefined;
  61944. };
  61945. /**
  61946. * Get a value from its key or add it if it doesn't exist.
  61947. * This method will ensure you that a given key/data will be present in the dictionary.
  61948. * @param key the given key to get the matching value from
  61949. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61950. * The factory will only be invoked if there's no data for the given key.
  61951. * @return the value corresponding to the key.
  61952. */
  61953. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61954. var val = this.get(key);
  61955. if (val !== undefined) {
  61956. return val;
  61957. }
  61958. val = factory(key);
  61959. if (val) {
  61960. this.add(key, val);
  61961. }
  61962. return val;
  61963. };
  61964. /**
  61965. * Get a value from its key if present in the dictionary otherwise add it
  61966. * @param key the key to get the value from
  61967. * @param val if there's no such key/value pair in the dictionary add it with this value
  61968. * @return the value corresponding to the key
  61969. */
  61970. StringDictionary.prototype.getOrAdd = function (key, val) {
  61971. var curVal = this.get(key);
  61972. if (curVal !== undefined) {
  61973. return curVal;
  61974. }
  61975. this.add(key, val);
  61976. return val;
  61977. };
  61978. /**
  61979. * Check if there's a given key in the dictionary
  61980. * @param key the key to check for
  61981. * @return true if the key is present, false otherwise
  61982. */
  61983. StringDictionary.prototype.contains = function (key) {
  61984. return this._data[key] !== undefined;
  61985. };
  61986. /**
  61987. * Add a new key and its corresponding value
  61988. * @param key the key to add
  61989. * @param value the value corresponding to the key
  61990. * @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
  61991. */
  61992. StringDictionary.prototype.add = function (key, value) {
  61993. if (this._data[key] !== undefined) {
  61994. return false;
  61995. }
  61996. this._data[key] = value;
  61997. ++this._count;
  61998. return true;
  61999. };
  62000. StringDictionary.prototype.set = function (key, value) {
  62001. if (this._data[key] === undefined) {
  62002. return false;
  62003. }
  62004. this._data[key] = value;
  62005. return true;
  62006. };
  62007. /**
  62008. * Get the element of the given key and remove it from the dictionary
  62009. * @param key
  62010. */
  62011. StringDictionary.prototype.getAndRemove = function (key) {
  62012. var val = this.get(key);
  62013. if (val !== undefined) {
  62014. delete this._data[key];
  62015. --this._count;
  62016. return val;
  62017. }
  62018. return null;
  62019. };
  62020. /**
  62021. * Remove a key/value from the dictionary.
  62022. * @param key the key to remove
  62023. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62024. */
  62025. StringDictionary.prototype.remove = function (key) {
  62026. if (this.contains(key)) {
  62027. delete this._data[key];
  62028. --this._count;
  62029. return true;
  62030. }
  62031. return false;
  62032. };
  62033. /**
  62034. * Clear the whole content of the dictionary
  62035. */
  62036. StringDictionary.prototype.clear = function () {
  62037. this._data = {};
  62038. this._count = 0;
  62039. };
  62040. Object.defineProperty(StringDictionary.prototype, "count", {
  62041. get: function () {
  62042. return this._count;
  62043. },
  62044. enumerable: true,
  62045. configurable: true
  62046. });
  62047. /**
  62048. * Execute a callback on each key/val of the dictionary.
  62049. * Note that you can remove any element in this dictionary in the callback implementation
  62050. * @param callback the callback to execute on a given key/value pair
  62051. */
  62052. StringDictionary.prototype.forEach = function (callback) {
  62053. for (var cur in this._data) {
  62054. var val = this._data[cur];
  62055. callback(cur, val);
  62056. }
  62057. };
  62058. /**
  62059. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62060. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62061. * Note that you can remove any element in this dictionary in the callback implementation
  62062. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62063. */
  62064. StringDictionary.prototype.first = function (callback) {
  62065. for (var cur in this._data) {
  62066. var val = this._data[cur];
  62067. var res = callback(cur, val);
  62068. if (res) {
  62069. return res;
  62070. }
  62071. }
  62072. return null;
  62073. };
  62074. return StringDictionary;
  62075. }());
  62076. BABYLON.StringDictionary = StringDictionary;
  62077. })(BABYLON || (BABYLON = {}));
  62078. //# sourceMappingURL=babylon.stringDictionary.js.map
  62079. var BABYLON;
  62080. (function (BABYLON) {
  62081. var Tags = /** @class */ (function () {
  62082. function Tags() {
  62083. }
  62084. Tags.EnableFor = function (obj) {
  62085. obj._tags = obj._tags || {};
  62086. obj.hasTags = function () {
  62087. return Tags.HasTags(obj);
  62088. };
  62089. obj.addTags = function (tagsString) {
  62090. return Tags.AddTagsTo(obj, tagsString);
  62091. };
  62092. obj.removeTags = function (tagsString) {
  62093. return Tags.RemoveTagsFrom(obj, tagsString);
  62094. };
  62095. obj.matchesTagsQuery = function (tagsQuery) {
  62096. return Tags.MatchesQuery(obj, tagsQuery);
  62097. };
  62098. };
  62099. Tags.DisableFor = function (obj) {
  62100. delete obj._tags;
  62101. delete obj.hasTags;
  62102. delete obj.addTags;
  62103. delete obj.removeTags;
  62104. delete obj.matchesTagsQuery;
  62105. };
  62106. Tags.HasTags = function (obj) {
  62107. if (!obj._tags) {
  62108. return false;
  62109. }
  62110. return !BABYLON.Tools.IsEmpty(obj._tags);
  62111. };
  62112. Tags.GetTags = function (obj, asString) {
  62113. if (asString === void 0) { asString = true; }
  62114. if (!obj._tags) {
  62115. return null;
  62116. }
  62117. if (asString) {
  62118. var tagsArray = [];
  62119. for (var tag in obj._tags) {
  62120. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  62121. tagsArray.push(tag);
  62122. }
  62123. }
  62124. return tagsArray.join(" ");
  62125. }
  62126. else {
  62127. return obj._tags;
  62128. }
  62129. };
  62130. // the tags 'true' and 'false' are reserved and cannot be used as tags
  62131. // a tag cannot start with '||', '&&', and '!'
  62132. // it cannot contain whitespaces
  62133. Tags.AddTagsTo = function (obj, tagsString) {
  62134. if (!tagsString) {
  62135. return;
  62136. }
  62137. if (typeof tagsString !== "string") {
  62138. return;
  62139. }
  62140. var tags = tagsString.split(" ");
  62141. tags.forEach(function (tag, index, array) {
  62142. Tags._AddTagTo(obj, tag);
  62143. });
  62144. };
  62145. Tags._AddTagTo = function (obj, tag) {
  62146. tag = tag.trim();
  62147. if (tag === "" || tag === "true" || tag === "false") {
  62148. return;
  62149. }
  62150. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  62151. return;
  62152. }
  62153. Tags.EnableFor(obj);
  62154. obj._tags[tag] = true;
  62155. };
  62156. Tags.RemoveTagsFrom = function (obj, tagsString) {
  62157. if (!Tags.HasTags(obj)) {
  62158. return;
  62159. }
  62160. var tags = tagsString.split(" ");
  62161. for (var t in tags) {
  62162. Tags._RemoveTagFrom(obj, tags[t]);
  62163. }
  62164. };
  62165. Tags._RemoveTagFrom = function (obj, tag) {
  62166. delete obj._tags[tag];
  62167. };
  62168. Tags.MatchesQuery = function (obj, tagsQuery) {
  62169. if (tagsQuery === undefined) {
  62170. return true;
  62171. }
  62172. if (tagsQuery === "") {
  62173. return Tags.HasTags(obj);
  62174. }
  62175. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  62176. };
  62177. return Tags;
  62178. }());
  62179. BABYLON.Tags = Tags;
  62180. })(BABYLON || (BABYLON = {}));
  62181. //# sourceMappingURL=babylon.tags.js.map
  62182. var BABYLON;
  62183. (function (BABYLON) {
  62184. var AndOrNotEvaluator = /** @class */ (function () {
  62185. function AndOrNotEvaluator() {
  62186. }
  62187. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  62188. if (!query.match(/\([^\(\)]*\)/g)) {
  62189. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  62190. }
  62191. else {
  62192. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  62193. // remove parenthesis
  62194. r = r.slice(1, r.length - 1);
  62195. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  62196. });
  62197. }
  62198. if (query === "true") {
  62199. return true;
  62200. }
  62201. if (query === "false") {
  62202. return false;
  62203. }
  62204. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  62205. };
  62206. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  62207. evaluateCallback = evaluateCallback || (function (r) {
  62208. return r === "true" ? true : false;
  62209. });
  62210. var result;
  62211. var or = parenthesisContent.split("||");
  62212. for (var i in or) {
  62213. if (or.hasOwnProperty(i)) {
  62214. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  62215. var and = ori.split("&&");
  62216. if (and.length > 1) {
  62217. for (var j = 0; j < and.length; ++j) {
  62218. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  62219. if (andj !== "true" && andj !== "false") {
  62220. if (andj[0] === "!") {
  62221. result = !evaluateCallback(andj.substring(1));
  62222. }
  62223. else {
  62224. result = evaluateCallback(andj);
  62225. }
  62226. }
  62227. else {
  62228. result = andj === "true" ? true : false;
  62229. }
  62230. if (!result) {
  62231. ori = "false";
  62232. break;
  62233. }
  62234. }
  62235. }
  62236. if (result || ori === "true") {
  62237. result = true;
  62238. break;
  62239. }
  62240. // result equals false (or undefined)
  62241. if (ori !== "true" && ori !== "false") {
  62242. if (ori[0] === "!") {
  62243. result = !evaluateCallback(ori.substring(1));
  62244. }
  62245. else {
  62246. result = evaluateCallback(ori);
  62247. }
  62248. }
  62249. else {
  62250. result = ori === "true" ? true : false;
  62251. }
  62252. }
  62253. }
  62254. // the whole parenthesis scope is replaced by 'true' or 'false'
  62255. return result ? "true" : "false";
  62256. };
  62257. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62258. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62259. // remove whitespaces
  62260. r = r.replace(/[\s]/g, function () { return ""; });
  62261. return r.length % 2 ? "!" : "";
  62262. });
  62263. booleanString = booleanString.trim();
  62264. if (booleanString === "!true") {
  62265. booleanString = "false";
  62266. }
  62267. else if (booleanString === "!false") {
  62268. booleanString = "true";
  62269. }
  62270. return booleanString;
  62271. };
  62272. return AndOrNotEvaluator;
  62273. }());
  62274. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  62275. })(BABYLON || (BABYLON = {}));
  62276. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  62277. var BABYLON;
  62278. (function (BABYLON) {
  62279. var Database = /** @class */ (function () {
  62280. function Database(urlToScene, callbackManifestChecked) {
  62281. // Handling various flavors of prefixed version of IndexedDB
  62282. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  62283. this.callbackManifestChecked = callbackManifestChecked;
  62284. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  62285. this.db = null;
  62286. this._enableSceneOffline = false;
  62287. this._enableTexturesOffline = false;
  62288. this.manifestVersionFound = 0;
  62289. this.mustUpdateRessources = false;
  62290. this.hasReachedQuota = false;
  62291. if (!Database.IDBStorageEnabled) {
  62292. this.callbackManifestChecked(true);
  62293. }
  62294. else {
  62295. this.checkManifestFile();
  62296. }
  62297. }
  62298. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  62299. get: function () {
  62300. return this._enableSceneOffline;
  62301. },
  62302. enumerable: true,
  62303. configurable: true
  62304. });
  62305. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  62306. get: function () {
  62307. return this._enableTexturesOffline;
  62308. },
  62309. enumerable: true,
  62310. configurable: true
  62311. });
  62312. Database.prototype.checkManifestFile = function () {
  62313. var _this = this;
  62314. var noManifestFile = function () {
  62315. _this._enableSceneOffline = false;
  62316. _this._enableTexturesOffline = false;
  62317. _this.callbackManifestChecked(false);
  62318. };
  62319. var timeStampUsed = false;
  62320. var manifestURL = this.currentSceneUrl + ".manifest";
  62321. var xhr = new XMLHttpRequest();
  62322. if (navigator.onLine) {
  62323. // Adding a timestamp to by-pass browsers' cache
  62324. timeStampUsed = true;
  62325. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  62326. }
  62327. xhr.open("GET", manifestURL, true);
  62328. xhr.addEventListener("load", function () {
  62329. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62330. try {
  62331. var manifestFile = JSON.parse(xhr.response);
  62332. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  62333. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  62334. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  62335. _this.manifestVersionFound = manifestFile.version;
  62336. }
  62337. if (_this.callbackManifestChecked) {
  62338. _this.callbackManifestChecked(true);
  62339. }
  62340. }
  62341. catch (ex) {
  62342. noManifestFile();
  62343. }
  62344. }
  62345. else {
  62346. noManifestFile();
  62347. }
  62348. }, false);
  62349. xhr.addEventListener("error", function (event) {
  62350. if (timeStampUsed) {
  62351. timeStampUsed = false;
  62352. // Let's retry without the timeStamp
  62353. // It could fail when coupled with HTML5 Offline API
  62354. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  62355. xhr.open("GET", retryManifestURL, true);
  62356. xhr.send();
  62357. }
  62358. else {
  62359. noManifestFile();
  62360. }
  62361. }, false);
  62362. try {
  62363. xhr.send();
  62364. }
  62365. catch (ex) {
  62366. BABYLON.Tools.Error("Error on XHR send request.");
  62367. this.callbackManifestChecked(false);
  62368. }
  62369. };
  62370. Database.prototype.openAsync = function (successCallback, errorCallback) {
  62371. var _this = this;
  62372. var handleError = function () {
  62373. _this.isSupported = false;
  62374. if (errorCallback)
  62375. errorCallback();
  62376. };
  62377. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  62378. // Your browser doesn't support IndexedDB
  62379. this.isSupported = false;
  62380. if (errorCallback)
  62381. errorCallback();
  62382. }
  62383. else {
  62384. // If the DB hasn't been opened or created yet
  62385. if (!this.db) {
  62386. this.hasReachedQuota = false;
  62387. this.isSupported = true;
  62388. var request = this.idbFactory.open("babylonjs", 1);
  62389. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  62390. request.onerror = function (event) {
  62391. handleError();
  62392. };
  62393. // executes when a version change transaction cannot complete due to other active transactions
  62394. request.onblocked = function (event) {
  62395. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  62396. handleError();
  62397. };
  62398. // DB has been opened successfully
  62399. request.onsuccess = function (event) {
  62400. _this.db = request.result;
  62401. successCallback();
  62402. };
  62403. // Initialization of the DB. Creating Scenes & Textures stores
  62404. request.onupgradeneeded = function (event) {
  62405. _this.db = (event.target).result;
  62406. if (_this.db) {
  62407. try {
  62408. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  62409. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  62410. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  62411. }
  62412. catch (ex) {
  62413. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  62414. handleError();
  62415. }
  62416. }
  62417. };
  62418. }
  62419. else {
  62420. if (successCallback)
  62421. successCallback();
  62422. }
  62423. }
  62424. };
  62425. Database.prototype.loadImageFromDB = function (url, image) {
  62426. var _this = this;
  62427. var completeURL = Database.ReturnFullUrlLocation(url);
  62428. var saveAndLoadImage = function () {
  62429. if (!_this.hasReachedQuota && _this.db !== null) {
  62430. // the texture is not yet in the DB, let's try to save it
  62431. _this._saveImageIntoDBAsync(completeURL, image);
  62432. }
  62433. else {
  62434. image.src = url;
  62435. }
  62436. };
  62437. if (!this.mustUpdateRessources) {
  62438. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  62439. }
  62440. else {
  62441. saveAndLoadImage();
  62442. }
  62443. };
  62444. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  62445. if (this.isSupported && this.db !== null) {
  62446. var texture;
  62447. var transaction = this.db.transaction(["textures"]);
  62448. transaction.onabort = function (event) {
  62449. image.src = url;
  62450. };
  62451. transaction.oncomplete = function (event) {
  62452. var blobTextureURL;
  62453. if (texture) {
  62454. var URL = window.URL || window.webkitURL;
  62455. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  62456. image.onerror = function () {
  62457. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  62458. image.src = url;
  62459. };
  62460. image.src = blobTextureURL;
  62461. }
  62462. else {
  62463. notInDBCallback();
  62464. }
  62465. };
  62466. var getRequest = transaction.objectStore("textures").get(url);
  62467. getRequest.onsuccess = function (event) {
  62468. texture = (event.target).result;
  62469. };
  62470. getRequest.onerror = function (event) {
  62471. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  62472. image.src = url;
  62473. };
  62474. }
  62475. else {
  62476. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62477. image.src = url;
  62478. }
  62479. };
  62480. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  62481. var _this = this;
  62482. if (this.isSupported) {
  62483. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  62484. var generateBlobUrl = function () {
  62485. var blobTextureURL;
  62486. if (blob) {
  62487. var URL = window.URL || window.webkitURL;
  62488. try {
  62489. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  62490. }
  62491. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  62492. catch (ex) {
  62493. blobTextureURL = URL.createObjectURL(blob);
  62494. }
  62495. }
  62496. if (blobTextureURL) {
  62497. image.src = blobTextureURL;
  62498. }
  62499. };
  62500. if (Database.IsUASupportingBlobStorage) {
  62501. var xhr = new XMLHttpRequest(), blob;
  62502. xhr.open("GET", url, true);
  62503. xhr.responseType = "blob";
  62504. xhr.addEventListener("load", function () {
  62505. if (xhr.status === 200 && _this.db) {
  62506. // Blob as response (XHR2)
  62507. blob = xhr.response;
  62508. var transaction = _this.db.transaction(["textures"], "readwrite");
  62509. // the transaction could abort because of a QuotaExceededError error
  62510. transaction.onabort = function (event) {
  62511. try {
  62512. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62513. var srcElement = (event.srcElement || event.target);
  62514. var error = srcElement.error;
  62515. if (error && error.name === "QuotaExceededError") {
  62516. _this.hasReachedQuota = true;
  62517. }
  62518. }
  62519. catch (ex) { }
  62520. generateBlobUrl();
  62521. };
  62522. transaction.oncomplete = function (event) {
  62523. generateBlobUrl();
  62524. };
  62525. var newTexture = { textureUrl: url, data: blob };
  62526. try {
  62527. // Put the blob into the dabase
  62528. var addRequest = transaction.objectStore("textures").put(newTexture);
  62529. addRequest.onsuccess = function (event) {
  62530. };
  62531. addRequest.onerror = function (event) {
  62532. generateBlobUrl();
  62533. };
  62534. }
  62535. catch (ex) {
  62536. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  62537. if (ex.code === 25) {
  62538. Database.IsUASupportingBlobStorage = false;
  62539. }
  62540. image.src = url;
  62541. }
  62542. }
  62543. else {
  62544. image.src = url;
  62545. }
  62546. }, false);
  62547. xhr.addEventListener("error", function (event) {
  62548. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  62549. image.src = url;
  62550. }, false);
  62551. xhr.send();
  62552. }
  62553. else {
  62554. image.src = url;
  62555. }
  62556. }
  62557. else {
  62558. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62559. image.src = url;
  62560. }
  62561. };
  62562. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  62563. var _this = this;
  62564. var updateVersion = function () {
  62565. // the version is not yet in the DB or we need to update it
  62566. _this._saveVersionIntoDBAsync(url, versionLoaded);
  62567. };
  62568. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  62569. };
  62570. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  62571. var _this = this;
  62572. if (this.isSupported && this.db) {
  62573. var version;
  62574. try {
  62575. var transaction = this.db.transaction(["versions"]);
  62576. transaction.oncomplete = function (event) {
  62577. if (version) {
  62578. // If the version in the JSON file is > than the version in DB
  62579. if (_this.manifestVersionFound > version.data) {
  62580. _this.mustUpdateRessources = true;
  62581. updateInDBCallback();
  62582. }
  62583. else {
  62584. callback(version.data);
  62585. }
  62586. }
  62587. else {
  62588. _this.mustUpdateRessources = true;
  62589. updateInDBCallback();
  62590. }
  62591. };
  62592. transaction.onabort = function (event) {
  62593. callback(-1);
  62594. };
  62595. var getRequest = transaction.objectStore("versions").get(url);
  62596. getRequest.onsuccess = function (event) {
  62597. version = (event.target).result;
  62598. };
  62599. getRequest.onerror = function (event) {
  62600. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  62601. callback(-1);
  62602. };
  62603. }
  62604. catch (ex) {
  62605. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  62606. callback(-1);
  62607. }
  62608. }
  62609. else {
  62610. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62611. callback(-1);
  62612. }
  62613. };
  62614. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  62615. var _this = this;
  62616. if (this.isSupported && !this.hasReachedQuota && this.db) {
  62617. try {
  62618. // Open a transaction to the database
  62619. var transaction = this.db.transaction(["versions"], "readwrite");
  62620. // the transaction could abort because of a QuotaExceededError error
  62621. transaction.onabort = function (event) {
  62622. try {
  62623. var error = event.srcElement['error'];
  62624. if (error && error.name === "QuotaExceededError") {
  62625. _this.hasReachedQuota = true;
  62626. }
  62627. }
  62628. catch (ex) { }
  62629. callback(-1);
  62630. };
  62631. transaction.oncomplete = function (event) {
  62632. callback(_this.manifestVersionFound);
  62633. };
  62634. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  62635. // Put the scene into the database
  62636. var addRequest = transaction.objectStore("versions").put(newVersion);
  62637. addRequest.onsuccess = function (event) {
  62638. };
  62639. addRequest.onerror = function (event) {
  62640. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  62641. };
  62642. }
  62643. catch (ex) {
  62644. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  62645. callback(-1);
  62646. }
  62647. }
  62648. else {
  62649. callback(-1);
  62650. }
  62651. };
  62652. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  62653. var _this = this;
  62654. var completeUrl = Database.ReturnFullUrlLocation(url);
  62655. var saveAndLoadFile = function () {
  62656. // the scene is not yet in the DB, let's try to save it
  62657. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  62658. };
  62659. this._checkVersionFromDB(completeUrl, function (version) {
  62660. if (version !== -1) {
  62661. if (!_this.mustUpdateRessources) {
  62662. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  62663. }
  62664. else {
  62665. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  62666. }
  62667. }
  62668. else {
  62669. if (errorCallback) {
  62670. errorCallback();
  62671. }
  62672. }
  62673. });
  62674. };
  62675. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  62676. if (this.isSupported && this.db) {
  62677. var targetStore;
  62678. if (url.indexOf(".babylon") !== -1) {
  62679. targetStore = "scenes";
  62680. }
  62681. else {
  62682. targetStore = "textures";
  62683. }
  62684. var file;
  62685. var transaction = this.db.transaction([targetStore]);
  62686. transaction.oncomplete = function (event) {
  62687. if (file) {
  62688. callback(file.data);
  62689. }
  62690. else {
  62691. notInDBCallback();
  62692. }
  62693. };
  62694. transaction.onabort = function (event) {
  62695. notInDBCallback();
  62696. };
  62697. var getRequest = transaction.objectStore(targetStore).get(url);
  62698. getRequest.onsuccess = function (event) {
  62699. file = (event.target).result;
  62700. };
  62701. getRequest.onerror = function (event) {
  62702. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  62703. notInDBCallback();
  62704. };
  62705. }
  62706. else {
  62707. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62708. callback();
  62709. }
  62710. };
  62711. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  62712. var _this = this;
  62713. if (this.isSupported) {
  62714. var targetStore;
  62715. if (url.indexOf(".babylon") !== -1) {
  62716. targetStore = "scenes";
  62717. }
  62718. else {
  62719. targetStore = "textures";
  62720. }
  62721. // Create XHR
  62722. var xhr = new XMLHttpRequest();
  62723. var fileData;
  62724. xhr.open("GET", url, true);
  62725. if (useArrayBuffer) {
  62726. xhr.responseType = "arraybuffer";
  62727. }
  62728. if (progressCallback) {
  62729. xhr.onprogress = progressCallback;
  62730. }
  62731. xhr.addEventListener("load", function () {
  62732. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  62733. // Blob as response (XHR2)
  62734. //fileData = xhr.responseText;
  62735. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  62736. if (!_this.hasReachedQuota && _this.db) {
  62737. // Open a transaction to the database
  62738. var transaction = _this.db.transaction([targetStore], "readwrite");
  62739. // the transaction could abort because of a QuotaExceededError error
  62740. transaction.onabort = function (event) {
  62741. try {
  62742. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62743. var error = event.srcElement['error'];
  62744. if (error && error.name === "QuotaExceededError") {
  62745. _this.hasReachedQuota = true;
  62746. }
  62747. }
  62748. catch (ex) { }
  62749. callback(fileData);
  62750. };
  62751. transaction.oncomplete = function (event) {
  62752. callback(fileData);
  62753. };
  62754. var newFile;
  62755. if (targetStore === "scenes") {
  62756. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  62757. }
  62758. else {
  62759. newFile = { textureUrl: url, data: fileData };
  62760. }
  62761. try {
  62762. // Put the scene into the database
  62763. var addRequest = transaction.objectStore(targetStore).put(newFile);
  62764. addRequest.onsuccess = function (event) {
  62765. };
  62766. addRequest.onerror = function (event) {
  62767. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  62768. };
  62769. }
  62770. catch (ex) {
  62771. callback(fileData);
  62772. }
  62773. }
  62774. else {
  62775. callback(fileData);
  62776. }
  62777. }
  62778. else {
  62779. callback();
  62780. }
  62781. }, false);
  62782. xhr.addEventListener("error", function (event) {
  62783. BABYLON.Tools.Error("error on XHR request.");
  62784. callback();
  62785. }, false);
  62786. xhr.send();
  62787. }
  62788. else {
  62789. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62790. callback();
  62791. }
  62792. };
  62793. Database.IsUASupportingBlobStorage = true;
  62794. Database.IDBStorageEnabled = true;
  62795. Database.parseURL = function (url) {
  62796. var a = document.createElement('a');
  62797. a.href = url;
  62798. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  62799. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  62800. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  62801. return absLocation;
  62802. };
  62803. Database.ReturnFullUrlLocation = function (url) {
  62804. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  62805. return (Database.parseURL(window.location.href) + url);
  62806. }
  62807. else {
  62808. return url;
  62809. }
  62810. };
  62811. return Database;
  62812. }());
  62813. BABYLON.Database = Database;
  62814. })(BABYLON || (BABYLON = {}));
  62815. //# sourceMappingURL=babylon.database.js.map
  62816. var BABYLON;
  62817. (function (BABYLON) {
  62818. var FresnelParameters = /** @class */ (function () {
  62819. function FresnelParameters() {
  62820. this._isEnabled = true;
  62821. this.leftColor = BABYLON.Color3.White();
  62822. this.rightColor = BABYLON.Color3.Black();
  62823. this.bias = 0;
  62824. this.power = 1;
  62825. }
  62826. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  62827. get: function () {
  62828. return this._isEnabled;
  62829. },
  62830. set: function (value) {
  62831. if (this._isEnabled === value) {
  62832. return;
  62833. }
  62834. this._isEnabled = value;
  62835. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  62836. },
  62837. enumerable: true,
  62838. configurable: true
  62839. });
  62840. FresnelParameters.prototype.clone = function () {
  62841. var newFresnelParameters = new FresnelParameters();
  62842. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  62843. return newFresnelParameters;
  62844. };
  62845. FresnelParameters.prototype.serialize = function () {
  62846. var serializationObject = {};
  62847. serializationObject.isEnabled = this.isEnabled;
  62848. serializationObject.leftColor = this.leftColor;
  62849. serializationObject.rightColor = this.rightColor;
  62850. serializationObject.bias = this.bias;
  62851. serializationObject.power = this.power;
  62852. return serializationObject;
  62853. };
  62854. FresnelParameters.Parse = function (parsedFresnelParameters) {
  62855. var fresnelParameters = new FresnelParameters();
  62856. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  62857. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  62858. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  62859. fresnelParameters.bias = parsedFresnelParameters.bias;
  62860. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  62861. return fresnelParameters;
  62862. };
  62863. return FresnelParameters;
  62864. }());
  62865. BABYLON.FresnelParameters = FresnelParameters;
  62866. })(BABYLON || (BABYLON = {}));
  62867. //# sourceMappingURL=babylon.fresnelParameters.js.map
  62868. var BABYLON;
  62869. (function (BABYLON) {
  62870. var MultiMaterial = /** @class */ (function (_super) {
  62871. __extends(MultiMaterial, _super);
  62872. function MultiMaterial(name, scene) {
  62873. var _this = _super.call(this, name, scene, true) || this;
  62874. scene.multiMaterials.push(_this);
  62875. _this.subMaterials = new Array();
  62876. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  62877. return _this;
  62878. }
  62879. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  62880. get: function () {
  62881. return this._subMaterials;
  62882. },
  62883. set: function (value) {
  62884. this._subMaterials = value;
  62885. this._hookArray(value);
  62886. },
  62887. enumerable: true,
  62888. configurable: true
  62889. });
  62890. MultiMaterial.prototype._hookArray = function (array) {
  62891. var _this = this;
  62892. var oldPush = array.push;
  62893. array.push = function () {
  62894. var items = [];
  62895. for (var _i = 0; _i < arguments.length; _i++) {
  62896. items[_i] = arguments[_i];
  62897. }
  62898. var result = oldPush.apply(array, items);
  62899. _this._markAllSubMeshesAsTexturesDirty();
  62900. return result;
  62901. };
  62902. var oldSplice = array.splice;
  62903. array.splice = function (index, deleteCount) {
  62904. var deleted = oldSplice.apply(array, [index, deleteCount]);
  62905. _this._markAllSubMeshesAsTexturesDirty();
  62906. return deleted;
  62907. };
  62908. };
  62909. // Properties
  62910. MultiMaterial.prototype.getSubMaterial = function (index) {
  62911. if (index < 0 || index >= this.subMaterials.length) {
  62912. return this.getScene().defaultMaterial;
  62913. }
  62914. return this.subMaterials[index];
  62915. };
  62916. MultiMaterial.prototype.getActiveTextures = function () {
  62917. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  62918. if (subMaterial) {
  62919. return subMaterial.getActiveTextures();
  62920. }
  62921. else {
  62922. return [];
  62923. }
  62924. }));
  62925. var _a;
  62926. };
  62927. // Methods
  62928. MultiMaterial.prototype.getClassName = function () {
  62929. return "MultiMaterial";
  62930. };
  62931. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  62932. for (var index = 0; index < this.subMaterials.length; index++) {
  62933. var subMaterial = this.subMaterials[index];
  62934. if (subMaterial) {
  62935. if (subMaterial.storeEffectOnSubMeshes) {
  62936. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  62937. return false;
  62938. }
  62939. continue;
  62940. }
  62941. if (!subMaterial.isReady(mesh)) {
  62942. return false;
  62943. }
  62944. }
  62945. }
  62946. return true;
  62947. };
  62948. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  62949. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  62950. for (var index = 0; index < this.subMaterials.length; index++) {
  62951. var subMaterial = null;
  62952. var current = this.subMaterials[index];
  62953. if (cloneChildren && current) {
  62954. subMaterial = current.clone(name + "-" + current.name);
  62955. }
  62956. else {
  62957. subMaterial = this.subMaterials[index];
  62958. }
  62959. newMultiMaterial.subMaterials.push(subMaterial);
  62960. }
  62961. return newMultiMaterial;
  62962. };
  62963. MultiMaterial.prototype.serialize = function () {
  62964. var serializationObject = {};
  62965. serializationObject.name = this.name;
  62966. serializationObject.id = this.id;
  62967. if (BABYLON.Tags) {
  62968. serializationObject.tags = BABYLON.Tags.GetTags(this);
  62969. }
  62970. serializationObject.materials = [];
  62971. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  62972. var subMat = this.subMaterials[matIndex];
  62973. if (subMat) {
  62974. serializationObject.materials.push(subMat.id);
  62975. }
  62976. else {
  62977. serializationObject.materials.push(null);
  62978. }
  62979. }
  62980. return serializationObject;
  62981. };
  62982. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62983. var scene = this.getScene();
  62984. if (!scene) {
  62985. return;
  62986. }
  62987. var index = scene.multiMaterials.indexOf(this);
  62988. if (index >= 0) {
  62989. scene.multiMaterials.splice(index, 1);
  62990. }
  62991. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62992. };
  62993. return MultiMaterial;
  62994. }(BABYLON.Material));
  62995. BABYLON.MultiMaterial = MultiMaterial;
  62996. })(BABYLON || (BABYLON = {}));
  62997. //# sourceMappingURL=babylon.multiMaterial.js.map
  62998. var BABYLON;
  62999. (function (BABYLON) {
  63000. var FreeCameraTouchInput = /** @class */ (function () {
  63001. function FreeCameraTouchInput() {
  63002. this._offsetX = null;
  63003. this._offsetY = null;
  63004. this._pointerPressed = new Array();
  63005. this.touchAngularSensibility = 200000.0;
  63006. this.touchMoveSensibility = 250.0;
  63007. }
  63008. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  63009. var _this = this;
  63010. var previousPosition = null;
  63011. if (this._pointerInput === undefined) {
  63012. this._onLostFocus = function (evt) {
  63013. _this._offsetX = null;
  63014. _this._offsetY = null;
  63015. };
  63016. this._pointerInput = function (p, s) {
  63017. var evt = p.event;
  63018. if (evt.pointerType === "mouse") {
  63019. return;
  63020. }
  63021. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  63022. if (!noPreventDefault) {
  63023. evt.preventDefault();
  63024. }
  63025. _this._pointerPressed.push(evt.pointerId);
  63026. if (_this._pointerPressed.length !== 1) {
  63027. return;
  63028. }
  63029. previousPosition = {
  63030. x: evt.clientX,
  63031. y: evt.clientY
  63032. };
  63033. }
  63034. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  63035. if (!noPreventDefault) {
  63036. evt.preventDefault();
  63037. }
  63038. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63039. if (index === -1) {
  63040. return;
  63041. }
  63042. _this._pointerPressed.splice(index, 1);
  63043. if (index != 0) {
  63044. return;
  63045. }
  63046. previousPosition = null;
  63047. _this._offsetX = null;
  63048. _this._offsetY = null;
  63049. }
  63050. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  63051. if (!noPreventDefault) {
  63052. evt.preventDefault();
  63053. }
  63054. if (!previousPosition) {
  63055. return;
  63056. }
  63057. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63058. if (index != 0) {
  63059. return;
  63060. }
  63061. _this._offsetX = evt.clientX - previousPosition.x;
  63062. _this._offsetY = -(evt.clientY - previousPosition.y);
  63063. }
  63064. };
  63065. }
  63066. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  63067. if (this._onLostFocus) {
  63068. element.addEventListener("blur", this._onLostFocus);
  63069. }
  63070. };
  63071. FreeCameraTouchInput.prototype.detachControl = function (element) {
  63072. if (this._pointerInput && element) {
  63073. if (this._observer) {
  63074. this.camera.getScene().onPointerObservable.remove(this._observer);
  63075. this._observer = null;
  63076. }
  63077. if (this._onLostFocus) {
  63078. element.removeEventListener("blur", this._onLostFocus);
  63079. this._onLostFocus = null;
  63080. }
  63081. this._pointerPressed = [];
  63082. this._offsetX = null;
  63083. this._offsetY = null;
  63084. }
  63085. };
  63086. FreeCameraTouchInput.prototype.checkInputs = function () {
  63087. if (this._offsetX && this._offsetY) {
  63088. var camera = this.camera;
  63089. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63090. if (this._pointerPressed.length > 1) {
  63091. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63092. }
  63093. else {
  63094. var speed = camera._computeLocalCameraSpeed();
  63095. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63096. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63097. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63098. }
  63099. }
  63100. };
  63101. FreeCameraTouchInput.prototype.getClassName = function () {
  63102. return "FreeCameraTouchInput";
  63103. };
  63104. FreeCameraTouchInput.prototype.getSimpleName = function () {
  63105. return "touch";
  63106. };
  63107. __decorate([
  63108. BABYLON.serialize()
  63109. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  63110. __decorate([
  63111. BABYLON.serialize()
  63112. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  63113. return FreeCameraTouchInput;
  63114. }());
  63115. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  63116. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  63117. })(BABYLON || (BABYLON = {}));
  63118. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  63119. var BABYLON;
  63120. (function (BABYLON) {
  63121. // We're mainly based on the logic defined into the FreeCamera code
  63122. var TouchCamera = /** @class */ (function (_super) {
  63123. __extends(TouchCamera, _super);
  63124. //-- end properties for backward compatibility for inputs
  63125. function TouchCamera(name, position, scene) {
  63126. var _this = _super.call(this, name, position, scene) || this;
  63127. _this.inputs.addTouch();
  63128. _this._setupInputs();
  63129. return _this;
  63130. }
  63131. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  63132. //-- Begin properties for backward compatibility for inputs
  63133. get: function () {
  63134. var touch = this.inputs.attached["touch"];
  63135. if (touch)
  63136. return touch.touchAngularSensibility;
  63137. return 0;
  63138. },
  63139. set: function (value) {
  63140. var touch = this.inputs.attached["touch"];
  63141. if (touch)
  63142. touch.touchAngularSensibility = value;
  63143. },
  63144. enumerable: true,
  63145. configurable: true
  63146. });
  63147. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  63148. get: function () {
  63149. var touch = this.inputs.attached["touch"];
  63150. if (touch)
  63151. return touch.touchMoveSensibility;
  63152. return 0;
  63153. },
  63154. set: function (value) {
  63155. var touch = this.inputs.attached["touch"];
  63156. if (touch)
  63157. touch.touchMoveSensibility = value;
  63158. },
  63159. enumerable: true,
  63160. configurable: true
  63161. });
  63162. TouchCamera.prototype.getClassName = function () {
  63163. return "TouchCamera";
  63164. };
  63165. TouchCamera.prototype._setupInputs = function () {
  63166. var mouse = this.inputs.attached["mouse"];
  63167. if (mouse) {
  63168. mouse.touchEnabled = false;
  63169. }
  63170. };
  63171. return TouchCamera;
  63172. }(BABYLON.FreeCamera));
  63173. BABYLON.TouchCamera = TouchCamera;
  63174. })(BABYLON || (BABYLON = {}));
  63175. //# sourceMappingURL=babylon.touchCamera.js.map
  63176. var BABYLON;
  63177. (function (BABYLON) {
  63178. var ProceduralTexture = /** @class */ (function (_super) {
  63179. __extends(ProceduralTexture, _super);
  63180. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  63181. if (fallbackTexture === void 0) { fallbackTexture = null; }
  63182. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63183. if (isCube === void 0) { isCube = false; }
  63184. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63185. _this.isCube = isCube;
  63186. _this.isEnabled = true;
  63187. _this._currentRefreshId = -1;
  63188. _this._refreshRate = 1;
  63189. _this._vertexBuffers = {};
  63190. _this._uniforms = new Array();
  63191. _this._samplers = new Array();
  63192. _this._textures = {};
  63193. _this._floats = {};
  63194. _this._floatsArrays = {};
  63195. _this._colors3 = {};
  63196. _this._colors4 = {};
  63197. _this._vectors2 = {};
  63198. _this._vectors3 = {};
  63199. _this._matrices = {};
  63200. _this._fallbackTextureUsed = false;
  63201. scene._proceduralTextures.push(_this);
  63202. _this._engine = scene.getEngine();
  63203. _this.name = name;
  63204. _this.isRenderTarget = true;
  63205. _this._size = size;
  63206. _this._generateMipMaps = generateMipMaps;
  63207. _this.setFragment(fragment);
  63208. _this._fallbackTexture = fallbackTexture;
  63209. if (isCube) {
  63210. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  63211. _this.setFloat("face", 0);
  63212. }
  63213. else {
  63214. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  63215. }
  63216. // VBO
  63217. var vertices = [];
  63218. vertices.push(1, 1);
  63219. vertices.push(-1, 1);
  63220. vertices.push(-1, -1);
  63221. vertices.push(1, -1);
  63222. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63223. _this._createIndexBuffer();
  63224. return _this;
  63225. }
  63226. ProceduralTexture.prototype._createIndexBuffer = function () {
  63227. var engine = this._engine;
  63228. // Indices
  63229. var indices = [];
  63230. indices.push(0);
  63231. indices.push(1);
  63232. indices.push(2);
  63233. indices.push(0);
  63234. indices.push(2);
  63235. indices.push(3);
  63236. this._indexBuffer = engine.createIndexBuffer(indices);
  63237. };
  63238. ProceduralTexture.prototype._rebuild = function () {
  63239. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63240. if (vb) {
  63241. vb._rebuild();
  63242. }
  63243. this._createIndexBuffer();
  63244. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63245. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63246. }
  63247. };
  63248. ProceduralTexture.prototype.reset = function () {
  63249. if (this._effect === undefined) {
  63250. return;
  63251. }
  63252. var engine = this._engine;
  63253. engine._releaseEffect(this._effect);
  63254. };
  63255. ProceduralTexture.prototype.isReady = function () {
  63256. var _this = this;
  63257. var engine = this._engine;
  63258. var shaders;
  63259. if (!this._fragment) {
  63260. return false;
  63261. }
  63262. if (this._fallbackTextureUsed) {
  63263. return true;
  63264. }
  63265. if (this._fragment.fragmentElement !== undefined) {
  63266. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63267. }
  63268. else {
  63269. shaders = { vertex: "procedural", fragment: this._fragment };
  63270. }
  63271. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  63272. _this.releaseInternalTexture();
  63273. if (_this._fallbackTexture) {
  63274. _this._texture = _this._fallbackTexture._texture;
  63275. if (_this._texture) {
  63276. _this._texture.incrementReferences();
  63277. }
  63278. }
  63279. _this._fallbackTextureUsed = true;
  63280. });
  63281. return this._effect.isReady();
  63282. };
  63283. ProceduralTexture.prototype.resetRefreshCounter = function () {
  63284. this._currentRefreshId = -1;
  63285. };
  63286. ProceduralTexture.prototype.setFragment = function (fragment) {
  63287. this._fragment = fragment;
  63288. };
  63289. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  63290. get: function () {
  63291. return this._refreshRate;
  63292. },
  63293. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63294. set: function (value) {
  63295. this._refreshRate = value;
  63296. this.resetRefreshCounter();
  63297. },
  63298. enumerable: true,
  63299. configurable: true
  63300. });
  63301. ProceduralTexture.prototype._shouldRender = function () {
  63302. if (!this.isEnabled || !this.isReady() || !this._texture) {
  63303. return false;
  63304. }
  63305. if (this._fallbackTextureUsed) {
  63306. return false;
  63307. }
  63308. if (this._currentRefreshId === -1) {
  63309. this._currentRefreshId = 1;
  63310. return true;
  63311. }
  63312. if (this.refreshRate === this._currentRefreshId) {
  63313. this._currentRefreshId = 1;
  63314. return true;
  63315. }
  63316. this._currentRefreshId++;
  63317. return false;
  63318. };
  63319. ProceduralTexture.prototype.getRenderSize = function () {
  63320. return this._size;
  63321. };
  63322. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  63323. if (this._fallbackTextureUsed) {
  63324. return;
  63325. }
  63326. this.releaseInternalTexture();
  63327. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  63328. };
  63329. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  63330. if (this._uniforms.indexOf(uniformName) === -1) {
  63331. this._uniforms.push(uniformName);
  63332. }
  63333. };
  63334. ProceduralTexture.prototype.setTexture = function (name, texture) {
  63335. if (this._samplers.indexOf(name) === -1) {
  63336. this._samplers.push(name);
  63337. }
  63338. this._textures[name] = texture;
  63339. return this;
  63340. };
  63341. ProceduralTexture.prototype.setFloat = function (name, value) {
  63342. this._checkUniform(name);
  63343. this._floats[name] = value;
  63344. return this;
  63345. };
  63346. ProceduralTexture.prototype.setFloats = function (name, value) {
  63347. this._checkUniform(name);
  63348. this._floatsArrays[name] = value;
  63349. return this;
  63350. };
  63351. ProceduralTexture.prototype.setColor3 = function (name, value) {
  63352. this._checkUniform(name);
  63353. this._colors3[name] = value;
  63354. return this;
  63355. };
  63356. ProceduralTexture.prototype.setColor4 = function (name, value) {
  63357. this._checkUniform(name);
  63358. this._colors4[name] = value;
  63359. return this;
  63360. };
  63361. ProceduralTexture.prototype.setVector2 = function (name, value) {
  63362. this._checkUniform(name);
  63363. this._vectors2[name] = value;
  63364. return this;
  63365. };
  63366. ProceduralTexture.prototype.setVector3 = function (name, value) {
  63367. this._checkUniform(name);
  63368. this._vectors3[name] = value;
  63369. return this;
  63370. };
  63371. ProceduralTexture.prototype.setMatrix = function (name, value) {
  63372. this._checkUniform(name);
  63373. this._matrices[name] = value;
  63374. return this;
  63375. };
  63376. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63377. var scene = this.getScene();
  63378. if (!scene) {
  63379. return;
  63380. }
  63381. var engine = this._engine;
  63382. // Render
  63383. engine.enableEffect(this._effect);
  63384. engine.setState(false);
  63385. // Texture
  63386. for (var name in this._textures) {
  63387. this._effect.setTexture(name, this._textures[name]);
  63388. }
  63389. // Float
  63390. for (name in this._floats) {
  63391. this._effect.setFloat(name, this._floats[name]);
  63392. }
  63393. // Floats
  63394. for (name in this._floatsArrays) {
  63395. this._effect.setArray(name, this._floatsArrays[name]);
  63396. }
  63397. // Color3
  63398. for (name in this._colors3) {
  63399. this._effect.setColor3(name, this._colors3[name]);
  63400. }
  63401. // Color4
  63402. for (name in this._colors4) {
  63403. var color = this._colors4[name];
  63404. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  63405. }
  63406. // Vector2
  63407. for (name in this._vectors2) {
  63408. this._effect.setVector2(name, this._vectors2[name]);
  63409. }
  63410. // Vector3
  63411. for (name in this._vectors3) {
  63412. this._effect.setVector3(name, this._vectors3[name]);
  63413. }
  63414. // Matrix
  63415. for (name in this._matrices) {
  63416. this._effect.setMatrix(name, this._matrices[name]);
  63417. }
  63418. if (!this._texture) {
  63419. return;
  63420. }
  63421. if (this.isCube) {
  63422. for (var face = 0; face < 6; face++) {
  63423. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  63424. // VBOs
  63425. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63426. this._effect.setFloat("face", face);
  63427. // Clear
  63428. engine.clear(scene.clearColor, true, true, true);
  63429. // Draw order
  63430. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63431. // Mipmaps
  63432. if (face === 5) {
  63433. engine.generateMipMapsForCubemap(this._texture);
  63434. }
  63435. }
  63436. }
  63437. else {
  63438. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  63439. // VBOs
  63440. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63441. // Clear
  63442. engine.clear(scene.clearColor, true, true, true);
  63443. // Draw order
  63444. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63445. }
  63446. // Unbind
  63447. engine.unBindFramebuffer(this._texture, this.isCube);
  63448. if (this.onGenerated) {
  63449. this.onGenerated();
  63450. }
  63451. };
  63452. ProceduralTexture.prototype.clone = function () {
  63453. var textureSize = this.getSize();
  63454. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  63455. // Base texture
  63456. newTexture.hasAlpha = this.hasAlpha;
  63457. newTexture.level = this.level;
  63458. // RenderTarget Texture
  63459. newTexture.coordinatesMode = this.coordinatesMode;
  63460. return newTexture;
  63461. };
  63462. ProceduralTexture.prototype.dispose = function () {
  63463. var scene = this.getScene();
  63464. if (!scene) {
  63465. return;
  63466. }
  63467. var index = scene._proceduralTextures.indexOf(this);
  63468. if (index >= 0) {
  63469. scene._proceduralTextures.splice(index, 1);
  63470. }
  63471. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63472. if (vertexBuffer) {
  63473. vertexBuffer.dispose();
  63474. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63475. }
  63476. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  63477. this._indexBuffer = null;
  63478. }
  63479. _super.prototype.dispose.call(this);
  63480. };
  63481. return ProceduralTexture;
  63482. }(BABYLON.Texture));
  63483. BABYLON.ProceduralTexture = ProceduralTexture;
  63484. })(BABYLON || (BABYLON = {}));
  63485. //# sourceMappingURL=babylon.proceduralTexture.js.map
  63486. var BABYLON;
  63487. (function (BABYLON) {
  63488. var CustomProceduralTexture = /** @class */ (function (_super) {
  63489. __extends(CustomProceduralTexture, _super);
  63490. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  63491. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  63492. _this._animate = true;
  63493. _this._time = 0;
  63494. _this._texturePath = texturePath;
  63495. //Try to load json
  63496. _this.loadJson(texturePath);
  63497. _this.refreshRate = 1;
  63498. return _this;
  63499. }
  63500. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  63501. var _this = this;
  63502. var noConfigFile = function () {
  63503. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  63504. try {
  63505. _this.setFragment(_this._texturePath);
  63506. }
  63507. catch (ex) {
  63508. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  63509. }
  63510. };
  63511. var configFileUrl = jsonUrl + "/config.json";
  63512. var xhr = new XMLHttpRequest();
  63513. xhr.open("GET", configFileUrl, true);
  63514. xhr.addEventListener("load", function () {
  63515. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63516. try {
  63517. _this._config = JSON.parse(xhr.response);
  63518. _this.updateShaderUniforms();
  63519. _this.updateTextures();
  63520. _this.setFragment(_this._texturePath + "/custom");
  63521. _this._animate = _this._config.animate;
  63522. _this.refreshRate = _this._config.refreshrate;
  63523. }
  63524. catch (ex) {
  63525. noConfigFile();
  63526. }
  63527. }
  63528. else {
  63529. noConfigFile();
  63530. }
  63531. }, false);
  63532. xhr.addEventListener("error", function () {
  63533. noConfigFile();
  63534. }, false);
  63535. try {
  63536. xhr.send();
  63537. }
  63538. catch (ex) {
  63539. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  63540. }
  63541. };
  63542. CustomProceduralTexture.prototype.isReady = function () {
  63543. if (!_super.prototype.isReady.call(this)) {
  63544. return false;
  63545. }
  63546. for (var name in this._textures) {
  63547. var texture = this._textures[name];
  63548. if (!texture.isReady()) {
  63549. return false;
  63550. }
  63551. }
  63552. return true;
  63553. };
  63554. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63555. var scene = this.getScene();
  63556. if (this._animate && scene) {
  63557. this._time += scene.getAnimationRatio() * 0.03;
  63558. this.updateShaderUniforms();
  63559. }
  63560. _super.prototype.render.call(this, useCameraPostProcess);
  63561. };
  63562. CustomProceduralTexture.prototype.updateTextures = function () {
  63563. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  63564. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  63565. }
  63566. };
  63567. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  63568. if (this._config) {
  63569. for (var j = 0; j < this._config.uniforms.length; j++) {
  63570. var uniform = this._config.uniforms[j];
  63571. switch (uniform.type) {
  63572. case "float":
  63573. this.setFloat(uniform.name, uniform.value);
  63574. break;
  63575. case "color3":
  63576. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  63577. break;
  63578. case "color4":
  63579. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  63580. break;
  63581. case "vector2":
  63582. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  63583. break;
  63584. case "vector3":
  63585. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  63586. break;
  63587. }
  63588. }
  63589. }
  63590. this.setFloat("time", this._time);
  63591. };
  63592. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  63593. get: function () {
  63594. return this._animate;
  63595. },
  63596. set: function (value) {
  63597. this._animate = value;
  63598. },
  63599. enumerable: true,
  63600. configurable: true
  63601. });
  63602. return CustomProceduralTexture;
  63603. }(BABYLON.ProceduralTexture));
  63604. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  63605. })(BABYLON || (BABYLON = {}));
  63606. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  63607. var BABYLON;
  63608. (function (BABYLON) {
  63609. var FreeCameraGamepadInput = /** @class */ (function () {
  63610. function FreeCameraGamepadInput() {
  63611. this.gamepadAngularSensibility = 200;
  63612. this.gamepadMoveSensibility = 40;
  63613. // private members
  63614. this._cameraTransform = BABYLON.Matrix.Identity();
  63615. this._deltaTransform = BABYLON.Vector3.Zero();
  63616. this._vector3 = BABYLON.Vector3.Zero();
  63617. this._vector2 = BABYLON.Vector2.Zero();
  63618. }
  63619. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63620. var _this = this;
  63621. var manager = this.camera.getScene().gamepadManager;
  63622. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63623. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63624. // prioritize XBOX gamepads.
  63625. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63626. _this.gamepad = gamepad;
  63627. }
  63628. }
  63629. });
  63630. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63631. if (_this.gamepad === gamepad) {
  63632. _this.gamepad = null;
  63633. }
  63634. });
  63635. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63636. };
  63637. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  63638. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63639. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63640. this.gamepad = null;
  63641. };
  63642. FreeCameraGamepadInput.prototype.checkInputs = function () {
  63643. if (this.gamepad && this.gamepad.leftStick) {
  63644. var camera = this.camera;
  63645. var LSValues = this.gamepad.leftStick;
  63646. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  63647. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63648. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  63649. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  63650. var RSValues = this.gamepad.rightStick;
  63651. if (RSValues) {
  63652. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  63653. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  63654. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  63655. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  63656. }
  63657. else {
  63658. RSValues = { x: 0, y: 0 };
  63659. }
  63660. if (!camera.rotationQuaternion) {
  63661. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  63662. }
  63663. else {
  63664. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  63665. }
  63666. var speed = camera._computeLocalCameraSpeed() * 50.0;
  63667. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  63668. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  63669. camera.cameraDirection.addInPlace(this._deltaTransform);
  63670. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  63671. camera.cameraRotation.addInPlace(this._vector2);
  63672. }
  63673. };
  63674. FreeCameraGamepadInput.prototype.getClassName = function () {
  63675. return "FreeCameraGamepadInput";
  63676. };
  63677. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  63678. return "gamepad";
  63679. };
  63680. __decorate([
  63681. BABYLON.serialize()
  63682. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  63683. __decorate([
  63684. BABYLON.serialize()
  63685. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63686. return FreeCameraGamepadInput;
  63687. }());
  63688. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  63689. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  63690. })(BABYLON || (BABYLON = {}));
  63691. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  63692. var BABYLON;
  63693. (function (BABYLON) {
  63694. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  63695. function ArcRotateCameraGamepadInput() {
  63696. this.gamepadRotationSensibility = 80;
  63697. this.gamepadMoveSensibility = 40;
  63698. }
  63699. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63700. var _this = this;
  63701. var manager = this.camera.getScene().gamepadManager;
  63702. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63703. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63704. // prioritize XBOX gamepads.
  63705. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63706. _this.gamepad = gamepad;
  63707. }
  63708. }
  63709. });
  63710. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63711. if (_this.gamepad === gamepad) {
  63712. _this.gamepad = null;
  63713. }
  63714. });
  63715. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63716. };
  63717. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  63718. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63719. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63720. this.gamepad = null;
  63721. };
  63722. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  63723. if (this.gamepad) {
  63724. var camera = this.camera;
  63725. var RSValues = this.gamepad.rightStick;
  63726. if (RSValues) {
  63727. if (RSValues.x != 0) {
  63728. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  63729. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  63730. camera.inertialAlphaOffset += normalizedRX;
  63731. }
  63732. }
  63733. if (RSValues.y != 0) {
  63734. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  63735. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  63736. camera.inertialBetaOffset += normalizedRY;
  63737. }
  63738. }
  63739. }
  63740. var LSValues = this.gamepad.leftStick;
  63741. if (LSValues && LSValues.y != 0) {
  63742. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63743. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  63744. this.camera.inertialRadiusOffset -= normalizedLY;
  63745. }
  63746. }
  63747. }
  63748. };
  63749. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  63750. return "ArcRotateCameraGamepadInput";
  63751. };
  63752. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  63753. return "gamepad";
  63754. };
  63755. __decorate([
  63756. BABYLON.serialize()
  63757. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  63758. __decorate([
  63759. BABYLON.serialize()
  63760. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63761. return ArcRotateCameraGamepadInput;
  63762. }());
  63763. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  63764. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  63765. })(BABYLON || (BABYLON = {}));
  63766. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  63767. var BABYLON;
  63768. (function (BABYLON) {
  63769. var GamepadManager = /** @class */ (function () {
  63770. function GamepadManager(_scene) {
  63771. var _this = this;
  63772. this._scene = _scene;
  63773. this._babylonGamepads = [];
  63774. this._oneGamepadConnected = false;
  63775. this._isMonitoring = false;
  63776. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  63777. if (!BABYLON.Tools.IsWindowObjectExist()) {
  63778. this._gamepadEventSupported = false;
  63779. }
  63780. else {
  63781. this._gamepadEventSupported = 'GamepadEvent' in window;
  63782. this._gamepadSupport = (navigator.getGamepads ||
  63783. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  63784. }
  63785. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  63786. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  63787. for (var i in _this._babylonGamepads) {
  63788. var gamepad = _this._babylonGamepads[i];
  63789. if (gamepad && gamepad._isConnected) {
  63790. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  63791. }
  63792. }
  63793. });
  63794. this._onGamepadConnectedEvent = function (evt) {
  63795. var gamepad = evt.gamepad;
  63796. if (gamepad.index in _this._babylonGamepads) {
  63797. if (_this._babylonGamepads[gamepad.index].isConnected) {
  63798. return;
  63799. }
  63800. }
  63801. var newGamepad;
  63802. if (_this._babylonGamepads[gamepad.index]) {
  63803. newGamepad = _this._babylonGamepads[gamepad.index];
  63804. newGamepad.browserGamepad = gamepad;
  63805. newGamepad._isConnected = true;
  63806. }
  63807. else {
  63808. newGamepad = _this._addNewGamepad(gamepad);
  63809. }
  63810. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63811. _this._startMonitoringGamepads();
  63812. };
  63813. this._onGamepadDisconnectedEvent = function (evt) {
  63814. var gamepad = evt.gamepad;
  63815. // Remove the gamepad from the list of gamepads to monitor.
  63816. for (var i in _this._babylonGamepads) {
  63817. if (_this._babylonGamepads[i].index === gamepad.index) {
  63818. var disconnectedGamepad = _this._babylonGamepads[i];
  63819. disconnectedGamepad._isConnected = false;
  63820. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  63821. break;
  63822. }
  63823. }
  63824. };
  63825. if (this._gamepadSupport) {
  63826. //first add already-connected gamepads
  63827. this._updateGamepadObjects();
  63828. if (this._babylonGamepads.length) {
  63829. this._startMonitoringGamepads();
  63830. }
  63831. // Checking if the gamepad connected event is supported (like in Firefox)
  63832. if (this._gamepadEventSupported) {
  63833. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  63834. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  63835. }
  63836. else {
  63837. this._startMonitoringGamepads();
  63838. }
  63839. }
  63840. }
  63841. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  63842. get: function () {
  63843. return this._babylonGamepads;
  63844. },
  63845. enumerable: true,
  63846. configurable: true
  63847. });
  63848. GamepadManager.prototype.getGamepadByType = function (type) {
  63849. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  63850. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  63851. var gamepad = _a[_i];
  63852. if (gamepad && gamepad.type === type) {
  63853. return gamepad;
  63854. }
  63855. }
  63856. return null;
  63857. };
  63858. GamepadManager.prototype.dispose = function () {
  63859. if (this._gamepadEventSupported) {
  63860. if (this._onGamepadConnectedEvent) {
  63861. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  63862. }
  63863. if (this._onGamepadDisconnectedEvent) {
  63864. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  63865. }
  63866. this._onGamepadConnectedEvent = null;
  63867. this._onGamepadDisconnectedEvent = null;
  63868. }
  63869. this._babylonGamepads.forEach(function (gamepad) {
  63870. gamepad.dispose();
  63871. });
  63872. this.onGamepadConnectedObservable.clear();
  63873. this.onGamepadDisconnectedObservable.clear();
  63874. this._oneGamepadConnected = false;
  63875. this._stopMonitoringGamepads();
  63876. this._babylonGamepads = [];
  63877. };
  63878. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  63879. if (!this._oneGamepadConnected) {
  63880. this._oneGamepadConnected = true;
  63881. }
  63882. var newGamepad;
  63883. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  63884. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  63885. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  63886. }
  63887. else if (gamepad.pose) {
  63888. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  63889. }
  63890. else {
  63891. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  63892. }
  63893. this._babylonGamepads[newGamepad.index] = newGamepad;
  63894. return newGamepad;
  63895. };
  63896. GamepadManager.prototype._startMonitoringGamepads = function () {
  63897. if (!this._isMonitoring) {
  63898. this._isMonitoring = true;
  63899. //back-comp
  63900. if (!this._scene) {
  63901. this._checkGamepadsStatus();
  63902. }
  63903. }
  63904. };
  63905. GamepadManager.prototype._stopMonitoringGamepads = function () {
  63906. this._isMonitoring = false;
  63907. };
  63908. GamepadManager.prototype._checkGamepadsStatus = function () {
  63909. var _this = this;
  63910. // Hack to be compatible Chrome
  63911. this._updateGamepadObjects();
  63912. for (var i in this._babylonGamepads) {
  63913. var gamepad = this._babylonGamepads[i];
  63914. if (!gamepad || !gamepad.isConnected) {
  63915. continue;
  63916. }
  63917. gamepad.update();
  63918. }
  63919. if (this._isMonitoring && !this._scene) {
  63920. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  63921. }
  63922. };
  63923. // This function is called only on Chrome, which does not properly support
  63924. // connection/disconnection events and forces you to recopy again the gamepad object
  63925. GamepadManager.prototype._updateGamepadObjects = function () {
  63926. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  63927. for (var i = 0; i < gamepads.length; i++) {
  63928. if (gamepads[i]) {
  63929. if (!this._babylonGamepads[gamepads[i].index]) {
  63930. var newGamepad = this._addNewGamepad(gamepads[i]);
  63931. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63932. }
  63933. else {
  63934. // Forced to copy again this object for Chrome for unknown reason
  63935. this._babylonGamepads[i].browserGamepad = gamepads[i];
  63936. if (!this._babylonGamepads[i].isConnected) {
  63937. this._babylonGamepads[i]._isConnected = true;
  63938. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  63939. }
  63940. }
  63941. }
  63942. }
  63943. };
  63944. return GamepadManager;
  63945. }());
  63946. BABYLON.GamepadManager = GamepadManager;
  63947. })(BABYLON || (BABYLON = {}));
  63948. //# sourceMappingURL=babylon.gamepadManager.js.map
  63949. var BABYLON;
  63950. (function (BABYLON) {
  63951. var StickValues = /** @class */ (function () {
  63952. function StickValues(x, y) {
  63953. this.x = x;
  63954. this.y = y;
  63955. }
  63956. return StickValues;
  63957. }());
  63958. BABYLON.StickValues = StickValues;
  63959. var Gamepad = /** @class */ (function () {
  63960. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  63961. if (leftStickX === void 0) { leftStickX = 0; }
  63962. if (leftStickY === void 0) { leftStickY = 1; }
  63963. if (rightStickX === void 0) { rightStickX = 2; }
  63964. if (rightStickY === void 0) { rightStickY = 3; }
  63965. this.id = id;
  63966. this.index = index;
  63967. this.browserGamepad = browserGamepad;
  63968. this._isConnected = true;
  63969. this._invertLeftStickY = false;
  63970. this.type = Gamepad.GAMEPAD;
  63971. this._leftStickAxisX = leftStickX;
  63972. this._leftStickAxisY = leftStickY;
  63973. this._rightStickAxisX = rightStickX;
  63974. this._rightStickAxisY = rightStickY;
  63975. if (this.browserGamepad.axes.length >= 2) {
  63976. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63977. }
  63978. if (this.browserGamepad.axes.length >= 4) {
  63979. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63980. }
  63981. }
  63982. Object.defineProperty(Gamepad.prototype, "isConnected", {
  63983. get: function () {
  63984. return this._isConnected;
  63985. },
  63986. enumerable: true,
  63987. configurable: true
  63988. });
  63989. Gamepad.prototype.onleftstickchanged = function (callback) {
  63990. this._onleftstickchanged = callback;
  63991. };
  63992. Gamepad.prototype.onrightstickchanged = function (callback) {
  63993. this._onrightstickchanged = callback;
  63994. };
  63995. Object.defineProperty(Gamepad.prototype, "leftStick", {
  63996. get: function () {
  63997. return this._leftStick;
  63998. },
  63999. set: function (newValues) {
  64000. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  64001. this._onleftstickchanged(newValues);
  64002. }
  64003. this._leftStick = newValues;
  64004. },
  64005. enumerable: true,
  64006. configurable: true
  64007. });
  64008. Object.defineProperty(Gamepad.prototype, "rightStick", {
  64009. get: function () {
  64010. return this._rightStick;
  64011. },
  64012. set: function (newValues) {
  64013. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  64014. this._onrightstickchanged(newValues);
  64015. }
  64016. this._rightStick = newValues;
  64017. },
  64018. enumerable: true,
  64019. configurable: true
  64020. });
  64021. Gamepad.prototype.update = function () {
  64022. if (this._leftStick) {
  64023. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64024. if (this._invertLeftStickY) {
  64025. this.leftStick.y *= -1;
  64026. }
  64027. }
  64028. if (this._rightStick) {
  64029. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64030. }
  64031. };
  64032. Gamepad.prototype.dispose = function () {
  64033. };
  64034. Gamepad.GAMEPAD = 0;
  64035. Gamepad.GENERIC = 1;
  64036. Gamepad.XBOX = 2;
  64037. Gamepad.POSE_ENABLED = 3;
  64038. return Gamepad;
  64039. }());
  64040. BABYLON.Gamepad = Gamepad;
  64041. var GenericPad = /** @class */ (function (_super) {
  64042. __extends(GenericPad, _super);
  64043. function GenericPad(id, index, browserGamepad) {
  64044. var _this = _super.call(this, id, index, browserGamepad) || this;
  64045. _this.onButtonDownObservable = new BABYLON.Observable();
  64046. _this.onButtonUpObservable = new BABYLON.Observable();
  64047. _this.type = Gamepad.GENERIC;
  64048. _this._buttons = new Array(browserGamepad.buttons.length);
  64049. return _this;
  64050. }
  64051. GenericPad.prototype.onbuttondown = function (callback) {
  64052. this._onbuttondown = callback;
  64053. };
  64054. GenericPad.prototype.onbuttonup = function (callback) {
  64055. this._onbuttonup = callback;
  64056. };
  64057. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  64058. if (newValue !== currentValue) {
  64059. if (newValue === 1) {
  64060. if (this._onbuttondown) {
  64061. this._onbuttondown(buttonIndex);
  64062. }
  64063. this.onButtonDownObservable.notifyObservers(buttonIndex);
  64064. }
  64065. if (newValue === 0) {
  64066. if (this._onbuttonup) {
  64067. this._onbuttonup(buttonIndex);
  64068. }
  64069. this.onButtonUpObservable.notifyObservers(buttonIndex);
  64070. }
  64071. }
  64072. return newValue;
  64073. };
  64074. GenericPad.prototype.update = function () {
  64075. _super.prototype.update.call(this);
  64076. for (var index = 0; index < this._buttons.length; index++) {
  64077. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  64078. }
  64079. };
  64080. GenericPad.prototype.dispose = function () {
  64081. _super.prototype.dispose.call(this);
  64082. this.onButtonDownObservable.clear();
  64083. this.onButtonUpObservable.clear();
  64084. };
  64085. return GenericPad;
  64086. }(Gamepad));
  64087. BABYLON.GenericPad = GenericPad;
  64088. })(BABYLON || (BABYLON = {}));
  64089. //# sourceMappingURL=babylon.gamepad.js.map
  64090. var BABYLON;
  64091. (function (BABYLON) {
  64092. var Xbox360Button;
  64093. (function (Xbox360Button) {
  64094. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64095. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64096. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64097. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64098. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64099. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64100. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64101. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64102. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64103. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  64104. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  64105. var Xbox360Dpad;
  64106. (function (Xbox360Dpad) {
  64107. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  64108. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  64109. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  64110. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  64111. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  64112. var Xbox360Pad = /** @class */ (function (_super) {
  64113. __extends(Xbox360Pad, _super);
  64114. function Xbox360Pad(id, index, gamepad, xboxOne) {
  64115. if (xboxOne === void 0) { xboxOne = false; }
  64116. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  64117. _this._leftTrigger = 0;
  64118. _this._rightTrigger = 0;
  64119. _this.onButtonDownObservable = new BABYLON.Observable();
  64120. _this.onButtonUpObservable = new BABYLON.Observable();
  64121. _this.onPadDownObservable = new BABYLON.Observable();
  64122. _this.onPadUpObservable = new BABYLON.Observable();
  64123. _this._buttonA = 0;
  64124. _this._buttonB = 0;
  64125. _this._buttonX = 0;
  64126. _this._buttonY = 0;
  64127. _this._buttonBack = 0;
  64128. _this._buttonStart = 0;
  64129. _this._buttonLB = 0;
  64130. _this._buttonRB = 0;
  64131. _this._buttonLeftStick = 0;
  64132. _this._buttonRightStick = 0;
  64133. _this._dPadUp = 0;
  64134. _this._dPadDown = 0;
  64135. _this._dPadLeft = 0;
  64136. _this._dPadRight = 0;
  64137. _this._isXboxOnePad = false;
  64138. _this.type = BABYLON.Gamepad.XBOX;
  64139. _this._isXboxOnePad = xboxOne;
  64140. return _this;
  64141. }
  64142. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  64143. this._onlefttriggerchanged = callback;
  64144. };
  64145. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  64146. this._onrighttriggerchanged = callback;
  64147. };
  64148. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  64149. get: function () {
  64150. return this._leftTrigger;
  64151. },
  64152. set: function (newValue) {
  64153. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  64154. this._onlefttriggerchanged(newValue);
  64155. }
  64156. this._leftTrigger = newValue;
  64157. },
  64158. enumerable: true,
  64159. configurable: true
  64160. });
  64161. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  64162. get: function () {
  64163. return this._rightTrigger;
  64164. },
  64165. set: function (newValue) {
  64166. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  64167. this._onrighttriggerchanged(newValue);
  64168. }
  64169. this._rightTrigger = newValue;
  64170. },
  64171. enumerable: true,
  64172. configurable: true
  64173. });
  64174. Xbox360Pad.prototype.onbuttondown = function (callback) {
  64175. this._onbuttondown = callback;
  64176. };
  64177. Xbox360Pad.prototype.onbuttonup = function (callback) {
  64178. this._onbuttonup = callback;
  64179. };
  64180. Xbox360Pad.prototype.ondpaddown = function (callback) {
  64181. this._ondpaddown = callback;
  64182. };
  64183. Xbox360Pad.prototype.ondpadup = function (callback) {
  64184. this._ondpadup = callback;
  64185. };
  64186. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  64187. if (newValue !== currentValue) {
  64188. if (newValue === 1) {
  64189. if (this._onbuttondown) {
  64190. this._onbuttondown(buttonType);
  64191. }
  64192. this.onButtonDownObservable.notifyObservers(buttonType);
  64193. }
  64194. if (newValue === 0) {
  64195. if (this._onbuttonup) {
  64196. this._onbuttonup(buttonType);
  64197. }
  64198. this.onButtonUpObservable.notifyObservers(buttonType);
  64199. }
  64200. }
  64201. return newValue;
  64202. };
  64203. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  64204. if (newValue !== currentValue) {
  64205. if (newValue === 1) {
  64206. if (this._ondpaddown) {
  64207. this._ondpaddown(buttonType);
  64208. }
  64209. this.onPadDownObservable.notifyObservers(buttonType);
  64210. }
  64211. if (newValue === 0) {
  64212. if (this._ondpadup) {
  64213. this._ondpadup(buttonType);
  64214. }
  64215. this.onPadUpObservable.notifyObservers(buttonType);
  64216. }
  64217. }
  64218. return newValue;
  64219. };
  64220. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  64221. get: function () {
  64222. return this._buttonA;
  64223. },
  64224. set: function (value) {
  64225. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  64226. },
  64227. enumerable: true,
  64228. configurable: true
  64229. });
  64230. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  64231. get: function () {
  64232. return this._buttonB;
  64233. },
  64234. set: function (value) {
  64235. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  64236. },
  64237. enumerable: true,
  64238. configurable: true
  64239. });
  64240. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64241. get: function () {
  64242. return this._buttonX;
  64243. },
  64244. set: function (value) {
  64245. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64246. },
  64247. enumerable: true,
  64248. configurable: true
  64249. });
  64250. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64251. get: function () {
  64252. return this._buttonY;
  64253. },
  64254. set: function (value) {
  64255. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64256. },
  64257. enumerable: true,
  64258. configurable: true
  64259. });
  64260. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64261. get: function () {
  64262. return this._buttonStart;
  64263. },
  64264. set: function (value) {
  64265. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64266. },
  64267. enumerable: true,
  64268. configurable: true
  64269. });
  64270. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64271. get: function () {
  64272. return this._buttonBack;
  64273. },
  64274. set: function (value) {
  64275. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  64276. },
  64277. enumerable: true,
  64278. configurable: true
  64279. });
  64280. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  64281. get: function () {
  64282. return this._buttonLB;
  64283. },
  64284. set: function (value) {
  64285. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  64286. },
  64287. enumerable: true,
  64288. configurable: true
  64289. });
  64290. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  64291. get: function () {
  64292. return this._buttonRB;
  64293. },
  64294. set: function (value) {
  64295. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  64296. },
  64297. enumerable: true,
  64298. configurable: true
  64299. });
  64300. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  64301. get: function () {
  64302. return this._buttonLeftStick;
  64303. },
  64304. set: function (value) {
  64305. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  64306. },
  64307. enumerable: true,
  64308. configurable: true
  64309. });
  64310. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  64311. get: function () {
  64312. return this._buttonRightStick;
  64313. },
  64314. set: function (value) {
  64315. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  64316. },
  64317. enumerable: true,
  64318. configurable: true
  64319. });
  64320. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  64321. get: function () {
  64322. return this._dPadUp;
  64323. },
  64324. set: function (value) {
  64325. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  64326. },
  64327. enumerable: true,
  64328. configurable: true
  64329. });
  64330. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  64331. get: function () {
  64332. return this._dPadDown;
  64333. },
  64334. set: function (value) {
  64335. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  64336. },
  64337. enumerable: true,
  64338. configurable: true
  64339. });
  64340. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  64341. get: function () {
  64342. return this._dPadLeft;
  64343. },
  64344. set: function (value) {
  64345. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  64346. },
  64347. enumerable: true,
  64348. configurable: true
  64349. });
  64350. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  64351. get: function () {
  64352. return this._dPadRight;
  64353. },
  64354. set: function (value) {
  64355. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  64356. },
  64357. enumerable: true,
  64358. configurable: true
  64359. });
  64360. Xbox360Pad.prototype.update = function () {
  64361. _super.prototype.update.call(this);
  64362. if (this._isXboxOnePad) {
  64363. this.buttonA = this.browserGamepad.buttons[0].value;
  64364. this.buttonB = this.browserGamepad.buttons[1].value;
  64365. this.buttonX = this.browserGamepad.buttons[2].value;
  64366. this.buttonY = this.browserGamepad.buttons[3].value;
  64367. this.buttonLB = this.browserGamepad.buttons[4].value;
  64368. this.buttonRB = this.browserGamepad.buttons[5].value;
  64369. this.leftTrigger = this.browserGamepad.axes[2];
  64370. this.rightTrigger = this.browserGamepad.axes[5];
  64371. this.buttonBack = this.browserGamepad.buttons[9].value;
  64372. this.buttonStart = this.browserGamepad.buttons[8].value;
  64373. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  64374. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  64375. this.dPadUp = this.browserGamepad.buttons[11].value;
  64376. this.dPadDown = this.browserGamepad.buttons[12].value;
  64377. this.dPadLeft = this.browserGamepad.buttons[13].value;
  64378. this.dPadRight = this.browserGamepad.buttons[14].value;
  64379. }
  64380. else {
  64381. this.buttonA = this.browserGamepad.buttons[0].value;
  64382. this.buttonB = this.browserGamepad.buttons[1].value;
  64383. this.buttonX = this.browserGamepad.buttons[2].value;
  64384. this.buttonY = this.browserGamepad.buttons[3].value;
  64385. this.buttonLB = this.browserGamepad.buttons[4].value;
  64386. this.buttonRB = this.browserGamepad.buttons[5].value;
  64387. this.leftTrigger = this.browserGamepad.buttons[6].value;
  64388. this.rightTrigger = this.browserGamepad.buttons[7].value;
  64389. this.buttonBack = this.browserGamepad.buttons[8].value;
  64390. this.buttonStart = this.browserGamepad.buttons[9].value;
  64391. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  64392. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  64393. this.dPadUp = this.browserGamepad.buttons[12].value;
  64394. this.dPadDown = this.browserGamepad.buttons[13].value;
  64395. this.dPadLeft = this.browserGamepad.buttons[14].value;
  64396. this.dPadRight = this.browserGamepad.buttons[15].value;
  64397. }
  64398. };
  64399. Xbox360Pad.prototype.dispose = function () {
  64400. _super.prototype.dispose.call(this);
  64401. this.onButtonDownObservable.clear();
  64402. this.onButtonUpObservable.clear();
  64403. this.onPadDownObservable.clear();
  64404. this.onPadUpObservable.clear();
  64405. };
  64406. return Xbox360Pad;
  64407. }(BABYLON.Gamepad));
  64408. BABYLON.Xbox360Pad = Xbox360Pad;
  64409. })(BABYLON || (BABYLON = {}));
  64410. //# sourceMappingURL=babylon.xboxGamepad.js.map
  64411. var BABYLON;
  64412. (function (BABYLON) {
  64413. var PoseEnabledControllerType;
  64414. (function (PoseEnabledControllerType) {
  64415. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  64416. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  64417. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  64418. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  64419. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  64420. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  64421. var PoseEnabledControllerHelper = /** @class */ (function () {
  64422. function PoseEnabledControllerHelper() {
  64423. }
  64424. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  64425. // Oculus Touch
  64426. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  64427. return new BABYLON.OculusTouchController(vrGamepad);
  64428. }
  64429. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  64430. return new BABYLON.WindowsMotionController(vrGamepad);
  64431. }
  64432. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  64433. return new BABYLON.ViveController(vrGamepad);
  64434. }
  64435. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  64436. return new BABYLON.GearVRController(vrGamepad);
  64437. }
  64438. else {
  64439. return new BABYLON.GenericController(vrGamepad);
  64440. }
  64441. };
  64442. return PoseEnabledControllerHelper;
  64443. }());
  64444. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  64445. var PoseEnabledController = /** @class */ (function (_super) {
  64446. __extends(PoseEnabledController, _super);
  64447. function PoseEnabledController(browserGamepad) {
  64448. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  64449. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  64450. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  64451. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  64452. // Represents device position and rotation in babylon space
  64453. _this.devicePosition = BABYLON.Vector3.Zero();
  64454. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64455. _this.deviceScaleFactor = 1;
  64456. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  64457. _this._deviceToWorld = BABYLON.Matrix.Identity();
  64458. _this._workingMatrix = BABYLON.Matrix.Identity();
  64459. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  64460. _this.controllerType = PoseEnabledControllerType.GENERIC;
  64461. _this.position = BABYLON.Vector3.Zero();
  64462. _this.rotationQuaternion = new BABYLON.Quaternion();
  64463. _this._calculatedPosition = BABYLON.Vector3.Zero();
  64464. _this._calculatedRotation = new BABYLON.Quaternion();
  64465. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  64466. return _this;
  64467. }
  64468. PoseEnabledController.prototype.update = function () {
  64469. _super.prototype.update.call(this);
  64470. var pose = this.browserGamepad.pose;
  64471. this.updateFromDevice(pose);
  64472. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  64473. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  64474. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  64475. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  64476. if (this._mesh) {
  64477. this._mesh.position.copyFrom(this.devicePosition);
  64478. if (this._mesh.rotationQuaternion) {
  64479. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64480. }
  64481. }
  64482. };
  64483. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  64484. if (poseData) {
  64485. this.rawPose = poseData;
  64486. if (poseData.position) {
  64487. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  64488. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  64489. this._deviceRoomPosition.z *= -1;
  64490. }
  64491. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  64492. this._calculatedPosition.addInPlace(this.position);
  64493. }
  64494. var pose = this.rawPose;
  64495. if (poseData.orientation && pose.orientation) {
  64496. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  64497. if (this._mesh) {
  64498. if (this._mesh.getScene().useRightHandedSystem) {
  64499. this._deviceRoomRotationQuaternion.z *= -1;
  64500. this._deviceRoomRotationQuaternion.w *= -1;
  64501. }
  64502. else {
  64503. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  64504. }
  64505. }
  64506. // if the camera is set, rotate to the camera's rotation
  64507. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  64508. }
  64509. }
  64510. };
  64511. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  64512. if (this._mesh) {
  64513. this._mesh.parent = null;
  64514. }
  64515. this._mesh = mesh;
  64516. if (this._poseControlledCamera) {
  64517. this._mesh.parent = this._poseControlledCamera;
  64518. }
  64519. if (!this._mesh.rotationQuaternion) {
  64520. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  64521. }
  64522. };
  64523. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  64524. this._poseControlledCamera = camera;
  64525. if (this._mesh) {
  64526. this._mesh.parent = this._poseControlledCamera;
  64527. }
  64528. };
  64529. PoseEnabledController.prototype.dispose = function () {
  64530. if (this._mesh) {
  64531. this._mesh.dispose();
  64532. }
  64533. this._mesh = null;
  64534. _super.prototype.dispose.call(this);
  64535. };
  64536. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  64537. get: function () {
  64538. return this._mesh;
  64539. },
  64540. enumerable: true,
  64541. configurable: true
  64542. });
  64543. PoseEnabledController.prototype.getForwardRay = function (length) {
  64544. if (length === void 0) { length = 100; }
  64545. if (!this.mesh) {
  64546. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  64547. }
  64548. var m = this.mesh.getWorldMatrix();
  64549. var origin = m.getTranslation();
  64550. var forward = new BABYLON.Vector3(0, 0, -1);
  64551. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64552. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64553. return new BABYLON.Ray(origin, direction, length);
  64554. };
  64555. return PoseEnabledController;
  64556. }(BABYLON.Gamepad));
  64557. BABYLON.PoseEnabledController = PoseEnabledController;
  64558. })(BABYLON || (BABYLON = {}));
  64559. //# sourceMappingURL=babylon.poseEnabledController.js.map
  64560. var BABYLON;
  64561. (function (BABYLON) {
  64562. var WebVRController = /** @class */ (function (_super) {
  64563. __extends(WebVRController, _super);
  64564. function WebVRController(vrGamepad) {
  64565. var _this = _super.call(this, vrGamepad) || this;
  64566. // Observables
  64567. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  64568. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  64569. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  64570. _this.onPadStateChangedObservable = new BABYLON.Observable();
  64571. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  64572. _this.pad = { x: 0, y: 0 };
  64573. // avoid GC, store state in a tmp object
  64574. _this._changes = {
  64575. pressChanged: false,
  64576. touchChanged: false,
  64577. valueChanged: false,
  64578. changed: false
  64579. };
  64580. _this._buttons = new Array(vrGamepad.buttons.length);
  64581. _this.hand = vrGamepad.hand;
  64582. return _this;
  64583. }
  64584. WebVRController.prototype.onButtonStateChange = function (callback) {
  64585. this._onButtonStateChange = callback;
  64586. };
  64587. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  64588. get: function () {
  64589. return this._defaultModel;
  64590. },
  64591. enumerable: true,
  64592. configurable: true
  64593. });
  64594. WebVRController.prototype.update = function () {
  64595. _super.prototype.update.call(this);
  64596. for (var index = 0; index < this._buttons.length; index++) {
  64597. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  64598. }
  64599. ;
  64600. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  64601. this.pad.x = this.leftStick.x;
  64602. this.pad.y = this.leftStick.y;
  64603. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  64604. }
  64605. };
  64606. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  64607. if (!newState) {
  64608. newState = {
  64609. pressed: false,
  64610. touched: false,
  64611. value: 0
  64612. };
  64613. }
  64614. if (!currentState) {
  64615. this._buttons[buttonIndex] = {
  64616. pressed: newState.pressed,
  64617. touched: newState.touched,
  64618. value: newState.value
  64619. };
  64620. return;
  64621. }
  64622. this._checkChanges(newState, currentState);
  64623. if (this._changes.changed) {
  64624. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  64625. this.handleButtonChange(buttonIndex, newState, this._changes);
  64626. }
  64627. this._buttons[buttonIndex].pressed = newState.pressed;
  64628. this._buttons[buttonIndex].touched = newState.touched;
  64629. // oculus triggers are never 0, thou not touched.
  64630. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  64631. };
  64632. WebVRController.prototype._checkChanges = function (newState, currentState) {
  64633. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  64634. this._changes.touchChanged = newState.touched !== currentState.touched;
  64635. this._changes.valueChanged = newState.value !== currentState.value;
  64636. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  64637. return this._changes;
  64638. };
  64639. WebVRController.prototype.dispose = function () {
  64640. _super.prototype.dispose.call(this);
  64641. this.onTriggerStateChangedObservable.clear();
  64642. this.onMainButtonStateChangedObservable.clear();
  64643. this.onSecondaryButtonStateChangedObservable.clear();
  64644. this.onPadStateChangedObservable.clear();
  64645. this.onPadValuesChangedObservable.clear();
  64646. };
  64647. return WebVRController;
  64648. }(BABYLON.PoseEnabledController));
  64649. BABYLON.WebVRController = WebVRController;
  64650. })(BABYLON || (BABYLON = {}));
  64651. //# sourceMappingURL=babylon.webVRController.js.map
  64652. var BABYLON;
  64653. (function (BABYLON) {
  64654. var OculusTouchController = /** @class */ (function (_super) {
  64655. __extends(OculusTouchController, _super);
  64656. function OculusTouchController(vrGamepad) {
  64657. var _this = _super.call(this, vrGamepad) || this;
  64658. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  64659. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  64660. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  64661. return _this;
  64662. }
  64663. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64664. var _this = this;
  64665. var meshName;
  64666. // Hand
  64667. if (this.hand === 'left') {
  64668. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  64669. }
  64670. else {
  64671. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  64672. }
  64673. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  64674. /*
  64675. Parent Mesh name: oculus_touch_left
  64676. - body
  64677. - trigger
  64678. - thumbstick
  64679. - grip
  64680. - button_y
  64681. - button_x
  64682. - button_enter
  64683. */
  64684. _this._defaultModel = newMeshes[1];
  64685. _this.attachToMesh(_this._defaultModel);
  64686. if (meshLoaded) {
  64687. meshLoaded(_this._defaultModel);
  64688. }
  64689. });
  64690. };
  64691. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  64692. // helper getters for left and right hand.
  64693. get: function () {
  64694. if (this.hand === 'right') {
  64695. return this.onMainButtonStateChangedObservable;
  64696. }
  64697. else {
  64698. throw new Error('No A button on left hand');
  64699. }
  64700. },
  64701. enumerable: true,
  64702. configurable: true
  64703. });
  64704. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  64705. get: function () {
  64706. if (this.hand === 'right') {
  64707. return this.onSecondaryButtonStateChangedObservable;
  64708. }
  64709. else {
  64710. throw new Error('No B button on left hand');
  64711. }
  64712. },
  64713. enumerable: true,
  64714. configurable: true
  64715. });
  64716. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  64717. get: function () {
  64718. if (this.hand === 'left') {
  64719. return this.onMainButtonStateChangedObservable;
  64720. }
  64721. else {
  64722. throw new Error('No X button on right hand');
  64723. }
  64724. },
  64725. enumerable: true,
  64726. configurable: true
  64727. });
  64728. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  64729. get: function () {
  64730. if (this.hand === 'left') {
  64731. return this.onSecondaryButtonStateChangedObservable;
  64732. }
  64733. else {
  64734. throw new Error('No Y button on right hand');
  64735. }
  64736. },
  64737. enumerable: true,
  64738. configurable: true
  64739. });
  64740. /*
  64741. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  64742. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  64743. 2) secondary trigger (same)
  64744. 3) A (right) X (left), touch, pressed = value
  64745. 4) B / Y
  64746. 5) thumb rest
  64747. */
  64748. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64749. var notifyObject = state; //{ state: state, changes: changes };
  64750. var triggerDirection = this.hand === 'right' ? -1 : 1;
  64751. switch (buttonIdx) {
  64752. case 0:
  64753. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64754. return;
  64755. case 1:// index trigger
  64756. if (this._defaultModel) {
  64757. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  64758. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  64759. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  64760. }
  64761. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64762. return;
  64763. case 2:// secondary trigger
  64764. if (this._defaultModel) {
  64765. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  64766. }
  64767. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  64768. return;
  64769. case 3:
  64770. if (this._defaultModel) {
  64771. if (notifyObject.pressed) {
  64772. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  64773. }
  64774. else {
  64775. (this._defaultModel.getChildren()[1]).position.y = 0;
  64776. }
  64777. }
  64778. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64779. return;
  64780. case 4:
  64781. if (this._defaultModel) {
  64782. if (notifyObject.pressed) {
  64783. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64784. }
  64785. else {
  64786. (this._defaultModel.getChildren()[2]).position.y = 0;
  64787. }
  64788. }
  64789. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64790. return;
  64791. case 5:
  64792. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  64793. return;
  64794. }
  64795. };
  64796. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  64797. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  64798. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  64799. return OculusTouchController;
  64800. }(BABYLON.WebVRController));
  64801. BABYLON.OculusTouchController = OculusTouchController;
  64802. })(BABYLON || (BABYLON = {}));
  64803. //# sourceMappingURL=babylon.oculusTouchController.js.map
  64804. var BABYLON;
  64805. (function (BABYLON) {
  64806. var ViveController = /** @class */ (function (_super) {
  64807. __extends(ViveController, _super);
  64808. function ViveController(vrGamepad) {
  64809. var _this = _super.call(this, vrGamepad) || this;
  64810. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  64811. _this._invertLeftStickY = true;
  64812. return _this;
  64813. }
  64814. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64815. var _this = this;
  64816. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  64817. /*
  64818. Parent Mesh name: ViveWand
  64819. - body
  64820. - r_gripper
  64821. - l_gripper
  64822. - menu_button
  64823. - system_button
  64824. - trackpad
  64825. - trigger
  64826. - LED
  64827. */
  64828. _this._defaultModel = newMeshes[1];
  64829. _this.attachToMesh(_this._defaultModel);
  64830. if (meshLoaded) {
  64831. meshLoaded(_this._defaultModel);
  64832. }
  64833. });
  64834. };
  64835. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  64836. get: function () {
  64837. return this.onMainButtonStateChangedObservable;
  64838. },
  64839. enumerable: true,
  64840. configurable: true
  64841. });
  64842. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  64843. get: function () {
  64844. return this.onMainButtonStateChangedObservable;
  64845. },
  64846. enumerable: true,
  64847. configurable: true
  64848. });
  64849. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  64850. get: function () {
  64851. return this.onSecondaryButtonStateChangedObservable;
  64852. },
  64853. enumerable: true,
  64854. configurable: true
  64855. });
  64856. /**
  64857. * Vive mapping:
  64858. * 0: touchpad
  64859. * 1: trigger
  64860. * 2: left AND right buttons
  64861. * 3: menu button
  64862. */
  64863. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64864. var notifyObject = state; //{ state: state, changes: changes };
  64865. switch (buttonIdx) {
  64866. case 0:
  64867. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64868. return;
  64869. case 1:// index trigger
  64870. if (this._defaultModel) {
  64871. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  64872. }
  64873. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64874. return;
  64875. case 2:// left AND right button
  64876. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64877. return;
  64878. case 3:
  64879. if (this._defaultModel) {
  64880. if (notifyObject.pressed) {
  64881. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64882. }
  64883. else {
  64884. (this._defaultModel.getChildren()[2]).position.y = 0;
  64885. }
  64886. }
  64887. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64888. return;
  64889. }
  64890. };
  64891. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  64892. ViveController.MODEL_FILENAME = 'wand.babylon';
  64893. return ViveController;
  64894. }(BABYLON.WebVRController));
  64895. BABYLON.ViveController = ViveController;
  64896. })(BABYLON || (BABYLON = {}));
  64897. //# sourceMappingURL=babylon.viveController.js.map
  64898. var BABYLON;
  64899. (function (BABYLON) {
  64900. var GenericController = /** @class */ (function (_super) {
  64901. __extends(GenericController, _super);
  64902. function GenericController(vrGamepad) {
  64903. return _super.call(this, vrGamepad) || this;
  64904. }
  64905. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64906. var _this = this;
  64907. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  64908. _this._defaultModel = newMeshes[1];
  64909. _this.attachToMesh(_this._defaultModel);
  64910. if (meshLoaded) {
  64911. meshLoaded(_this._defaultModel);
  64912. }
  64913. });
  64914. };
  64915. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64916. console.log("Button id: " + buttonIdx + "state: ");
  64917. console.dir(state);
  64918. };
  64919. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64920. GenericController.MODEL_FILENAME = 'generic.babylon';
  64921. return GenericController;
  64922. }(BABYLON.WebVRController));
  64923. BABYLON.GenericController = GenericController;
  64924. })(BABYLON || (BABYLON = {}));
  64925. //# sourceMappingURL=babylon.genericController.js.map
  64926. var BABYLON;
  64927. (function (BABYLON) {
  64928. var LoadedMeshInfo = /** @class */ (function () {
  64929. function LoadedMeshInfo() {
  64930. this.buttonMeshes = {};
  64931. this.axisMeshes = {};
  64932. }
  64933. return LoadedMeshInfo;
  64934. }());
  64935. var WindowsMotionController = /** @class */ (function (_super) {
  64936. __extends(WindowsMotionController, _super);
  64937. function WindowsMotionController(vrGamepad) {
  64938. var _this = _super.call(this, vrGamepad) || this;
  64939. _this._mapping = {
  64940. // Semantic button names
  64941. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  64942. // A mapping of the button name to glTF model node name
  64943. // that should be transformed by button value.
  64944. buttonMeshNames: {
  64945. 'trigger': 'SELECT',
  64946. 'menu': 'MENU',
  64947. 'grip': 'GRASP',
  64948. 'thumbstick': 'THUMBSTICK_PRESS',
  64949. 'trackpad': 'TOUCHPAD_PRESS'
  64950. },
  64951. // This mapping is used to translate from the Motion Controller to Babylon semantics
  64952. buttonObservableNames: {
  64953. 'trigger': 'onTriggerStateChangedObservable',
  64954. 'menu': 'onSecondaryButtonStateChangedObservable',
  64955. 'grip': 'onMainButtonStateChangedObservable',
  64956. 'thumbstick': 'onPadStateChangedObservable',
  64957. 'trackpad': 'onTrackpadChangedObservable'
  64958. },
  64959. // A mapping of the axis name to glTF model node name
  64960. // that should be transformed by axis value.
  64961. // This array mirrors the browserGamepad.axes array, such that
  64962. // the mesh corresponding to axis 0 is in this array index 0.
  64963. axisMeshNames: [
  64964. 'THUMBSTICK_X',
  64965. 'THUMBSTICK_Y',
  64966. 'TOUCHPAD_TOUCH_X',
  64967. 'TOUCHPAD_TOUCH_Y'
  64968. ],
  64969. pointingPoseMeshName: 'POINTING_POSE'
  64970. };
  64971. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  64972. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  64973. _this.trackpad = { x: 0, y: 0 };
  64974. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  64975. _this._loadedMeshInfo = null;
  64976. return _this;
  64977. }
  64978. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  64979. get: function () {
  64980. return this.onTriggerStateChangedObservable;
  64981. },
  64982. enumerable: true,
  64983. configurable: true
  64984. });
  64985. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  64986. get: function () {
  64987. return this.onSecondaryButtonStateChangedObservable;
  64988. },
  64989. enumerable: true,
  64990. configurable: true
  64991. });
  64992. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  64993. get: function () {
  64994. return this.onMainButtonStateChangedObservable;
  64995. },
  64996. enumerable: true,
  64997. configurable: true
  64998. });
  64999. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  65000. get: function () {
  65001. return this.onPadStateChangedObservable;
  65002. },
  65003. enumerable: true,
  65004. configurable: true
  65005. });
  65006. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  65007. get: function () {
  65008. return this.onTrackpadChangedObservable;
  65009. },
  65010. enumerable: true,
  65011. configurable: true
  65012. });
  65013. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  65014. get: function () {
  65015. return this.onTrackpadValuesChangedObservable;
  65016. },
  65017. enumerable: true,
  65018. configurable: true
  65019. });
  65020. /**
  65021. * Called once per frame by the engine.
  65022. */
  65023. WindowsMotionController.prototype.update = function () {
  65024. _super.prototype.update.call(this);
  65025. // Only need to animate axes if there is a loaded mesh
  65026. if (this._loadedMeshInfo) {
  65027. if (this.browserGamepad.axes) {
  65028. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  65029. this.trackpad.x = this.browserGamepad["axes"][2];
  65030. this.trackpad.y = this.browserGamepad["axes"][3];
  65031. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  65032. }
  65033. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  65034. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  65035. }
  65036. }
  65037. }
  65038. };
  65039. /**
  65040. * Called once for each button that changed state since the last frame
  65041. * @param buttonIdx Which button index changed
  65042. * @param state New state of the button
  65043. * @param changes Which properties on the state changed since last frame
  65044. */
  65045. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65046. var buttonName = this._mapping.buttons[buttonIdx];
  65047. if (!buttonName) {
  65048. return;
  65049. }
  65050. // Only emit events for buttons that we know how to map from index to name
  65051. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  65052. if (observable) {
  65053. observable.notifyObservers(state);
  65054. }
  65055. this.lerpButtonTransform(buttonName, state.value);
  65056. };
  65057. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  65058. // If there is no loaded mesh, there is nothing to transform.
  65059. if (!this._loadedMeshInfo) {
  65060. return;
  65061. }
  65062. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  65063. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65064. return;
  65065. }
  65066. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  65067. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  65068. };
  65069. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  65070. if (!this._loadedMeshInfo) {
  65071. return;
  65072. }
  65073. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  65074. if (!meshInfo) {
  65075. return;
  65076. }
  65077. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65078. return;
  65079. }
  65080. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65081. var lerpValue = axisValue * 0.5 + 0.5;
  65082. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65083. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65084. };
  65085. /**
  65086. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65087. * @param scene scene in which to add meshes
  65088. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  65089. */
  65090. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  65091. var _this = this;
  65092. if (forceDefault === void 0) { forceDefault = false; }
  65093. var path;
  65094. var filename;
  65095. // Checking if GLB loader is present
  65096. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  65097. // Determine the device specific folder based on the ID suffix
  65098. var device = 'default';
  65099. if (this.id && !forceDefault) {
  65100. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  65101. device = ((match && match[0]) || device);
  65102. }
  65103. // Hand
  65104. if (this.hand === 'left') {
  65105. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  65106. }
  65107. else {
  65108. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  65109. }
  65110. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  65111. }
  65112. else {
  65113. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  65114. path = BABYLON.GenericController.MODEL_BASE_URL;
  65115. filename = BABYLON.GenericController.MODEL_FILENAME;
  65116. }
  65117. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  65118. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  65119. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  65120. if (!_this._loadedMeshInfo) {
  65121. return;
  65122. }
  65123. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  65124. _this.attachToMesh(_this._defaultModel);
  65125. if (meshLoaded) {
  65126. meshLoaded(_this._defaultModel);
  65127. }
  65128. }, null, function (scene, message) {
  65129. BABYLON.Tools.Log(message);
  65130. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  65131. if (!forceDefault) {
  65132. _this.initControllerMesh(scene, meshLoaded, true);
  65133. }
  65134. });
  65135. };
  65136. /**
  65137. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  65138. * can be transformed by button presses and axes values, based on this._mapping.
  65139. *
  65140. * @param scene scene in which the meshes exist
  65141. * @param meshes list of meshes that make up the controller model to process
  65142. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  65143. */
  65144. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  65145. var loadedMeshInfo = null;
  65146. // Create a new mesh to contain the glTF hierarchy
  65147. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  65148. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  65149. var childMesh = null;
  65150. for (var i = 0; i < meshes.length; i++) {
  65151. var mesh = meshes[i];
  65152. if (!mesh.parent) {
  65153. // Exclude controller meshes from picking results
  65154. mesh.isPickable = false;
  65155. // Handle root node, attach to the new parentMesh
  65156. childMesh = mesh;
  65157. break;
  65158. }
  65159. }
  65160. if (childMesh) {
  65161. childMesh.setParent(parentMesh);
  65162. // Create our mesh info. Note that this method will always return non-null.
  65163. loadedMeshInfo = this.createMeshInfo(parentMesh);
  65164. }
  65165. else {
  65166. BABYLON.Tools.Warn('Could not find root node in model file.');
  65167. }
  65168. return loadedMeshInfo;
  65169. };
  65170. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  65171. var loadedMeshInfo = new LoadedMeshInfo();
  65172. var i;
  65173. loadedMeshInfo.rootNode = rootNode;
  65174. // Reset the caches
  65175. loadedMeshInfo.buttonMeshes = {};
  65176. loadedMeshInfo.axisMeshes = {};
  65177. // Button Meshes
  65178. for (i = 0; i < this._mapping.buttons.length; i++) {
  65179. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  65180. if (!buttonMeshName) {
  65181. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  65182. continue;
  65183. }
  65184. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  65185. if (!buttonMesh) {
  65186. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  65187. continue;
  65188. }
  65189. var buttonMeshInfo = {
  65190. index: i,
  65191. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  65192. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  65193. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  65194. };
  65195. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  65196. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  65197. }
  65198. else {
  65199. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  65200. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  65201. '(VALUE: ' + !!buttonMeshInfo.value +
  65202. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  65203. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  65204. ')');
  65205. }
  65206. }
  65207. // Axis Meshes
  65208. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  65209. var axisMeshName = this._mapping.axisMeshNames[i];
  65210. if (!axisMeshName) {
  65211. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  65212. continue;
  65213. }
  65214. var axisMesh = getChildByName(rootNode, axisMeshName);
  65215. if (!axisMesh) {
  65216. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  65217. continue;
  65218. }
  65219. var axisMeshInfo = {
  65220. index: i,
  65221. value: getImmediateChildByName(axisMesh, 'VALUE'),
  65222. min: getImmediateChildByName(axisMesh, 'MIN'),
  65223. max: getImmediateChildByName(axisMesh, 'MAX')
  65224. };
  65225. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  65226. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  65227. }
  65228. else {
  65229. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  65230. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65231. '(VALUE: ' + !!axisMeshInfo.value +
  65232. ', MIN: ' + !!axisMeshInfo.min +
  65233. ', MAX:' + !!axisMeshInfo.max +
  65234. ')');
  65235. }
  65236. }
  65237. // Pointing Ray
  65238. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65239. if (!loadedMeshInfo.pointingPoseNode) {
  65240. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65241. }
  65242. return loadedMeshInfo;
  65243. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65244. function getChildByName(node, name) {
  65245. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65246. }
  65247. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65248. function getImmediateChildByName(node, name) {
  65249. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65250. }
  65251. };
  65252. WindowsMotionController.prototype.getForwardRay = function (length) {
  65253. if (length === void 0) { length = 100; }
  65254. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65255. return _super.prototype.getForwardRay.call(this, length);
  65256. }
  65257. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  65258. var origin = m.getTranslation();
  65259. var forward = new BABYLON.Vector3(0, 0, -1);
  65260. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65261. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65262. return new BABYLON.Ray(origin, direction, length);
  65263. };
  65264. WindowsMotionController.prototype.dispose = function () {
  65265. _super.prototype.dispose.call(this);
  65266. this.onTrackpadChangedObservable.clear();
  65267. };
  65268. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  65269. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  65270. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  65271. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  65272. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  65273. return WindowsMotionController;
  65274. }(BABYLON.WebVRController));
  65275. BABYLON.WindowsMotionController = WindowsMotionController;
  65276. })(BABYLON || (BABYLON = {}));
  65277. //# sourceMappingURL=babylon.windowsMotionController.js.map
  65278. var BABYLON;
  65279. (function (BABYLON) {
  65280. var GearVRController = /** @class */ (function (_super) {
  65281. __extends(GearVRController, _super);
  65282. function GearVRController(vrGamepad) {
  65283. var _this = _super.call(this, vrGamepad) || this;
  65284. _this._buttonIndexToObservableNameMap = [
  65285. 'onTrackpadChangedObservable',
  65286. 'onTriggerStateChangedObservable' // Trigger
  65287. ];
  65288. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  65289. return _this;
  65290. }
  65291. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65292. var _this = this;
  65293. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  65294. _this._defaultModel = newMeshes[1];
  65295. _this.attachToMesh(_this._defaultModel);
  65296. if (meshLoaded) {
  65297. meshLoaded(_this._defaultModel);
  65298. }
  65299. });
  65300. };
  65301. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65302. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  65303. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  65304. // Only emit events for buttons that we know how to map from index to observable
  65305. var observable = this[observableName];
  65306. if (observable) {
  65307. observable.notifyObservers(state);
  65308. }
  65309. }
  65310. };
  65311. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65312. GearVRController.MODEL_FILENAME = 'generic.babylon';
  65313. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  65314. return GearVRController;
  65315. }(BABYLON.WebVRController));
  65316. BABYLON.GearVRController = GearVRController;
  65317. })(BABYLON || (BABYLON = {}));
  65318. //# sourceMappingURL=babylon.gearVRController.js.map
  65319. var BABYLON;
  65320. (function (BABYLON) {
  65321. var FollowCamera = /** @class */ (function (_super) {
  65322. __extends(FollowCamera, _super);
  65323. function FollowCamera(name, position, scene, lockedTarget) {
  65324. if (lockedTarget === void 0) { lockedTarget = null; }
  65325. var _this = _super.call(this, name, position, scene) || this;
  65326. _this.radius = 12;
  65327. _this.rotationOffset = 0;
  65328. _this.heightOffset = 4;
  65329. _this.cameraAcceleration = 0.05;
  65330. _this.maxCameraSpeed = 20;
  65331. _this.lockedTarget = lockedTarget;
  65332. return _this;
  65333. }
  65334. FollowCamera.prototype.getRadians = function (degrees) {
  65335. return degrees * Math.PI / 180;
  65336. };
  65337. FollowCamera.prototype.follow = function (cameraTarget) {
  65338. if (!cameraTarget)
  65339. return;
  65340. var yRotation;
  65341. if (cameraTarget.rotationQuaternion) {
  65342. var rotMatrix = new BABYLON.Matrix();
  65343. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  65344. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  65345. }
  65346. else {
  65347. yRotation = cameraTarget.rotation.y;
  65348. }
  65349. var radians = this.getRadians(this.rotationOffset) + yRotation;
  65350. var targetPosition = cameraTarget.getAbsolutePosition();
  65351. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  65352. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  65353. var dx = targetX - this.position.x;
  65354. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  65355. var dz = (targetZ) - this.position.z;
  65356. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  65357. var vy = dy * this.cameraAcceleration;
  65358. var vz = dz * this.cameraAcceleration * 2;
  65359. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  65360. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65361. }
  65362. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  65363. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65364. }
  65365. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  65366. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65367. }
  65368. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  65369. this.setTarget(targetPosition);
  65370. };
  65371. FollowCamera.prototype._checkInputs = function () {
  65372. _super.prototype._checkInputs.call(this);
  65373. if (this.lockedTarget) {
  65374. this.follow(this.lockedTarget);
  65375. }
  65376. };
  65377. FollowCamera.prototype.getClassName = function () {
  65378. return "FollowCamera";
  65379. };
  65380. __decorate([
  65381. BABYLON.serialize()
  65382. ], FollowCamera.prototype, "radius", void 0);
  65383. __decorate([
  65384. BABYLON.serialize()
  65385. ], FollowCamera.prototype, "rotationOffset", void 0);
  65386. __decorate([
  65387. BABYLON.serialize()
  65388. ], FollowCamera.prototype, "heightOffset", void 0);
  65389. __decorate([
  65390. BABYLON.serialize()
  65391. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  65392. __decorate([
  65393. BABYLON.serialize()
  65394. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  65395. __decorate([
  65396. BABYLON.serializeAsMeshReference("lockedTargetId")
  65397. ], FollowCamera.prototype, "lockedTarget", void 0);
  65398. return FollowCamera;
  65399. }(BABYLON.TargetCamera));
  65400. BABYLON.FollowCamera = FollowCamera;
  65401. var ArcFollowCamera = /** @class */ (function (_super) {
  65402. __extends(ArcFollowCamera, _super);
  65403. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  65404. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  65405. _this.alpha = alpha;
  65406. _this.beta = beta;
  65407. _this.radius = radius;
  65408. _this.target = target;
  65409. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  65410. _this.follow();
  65411. return _this;
  65412. }
  65413. ArcFollowCamera.prototype.follow = function () {
  65414. if (!this.target) {
  65415. return;
  65416. }
  65417. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  65418. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  65419. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  65420. var targetPosition = this.target.getAbsolutePosition();
  65421. this.position = targetPosition.add(this._cartesianCoordinates);
  65422. this.setTarget(targetPosition);
  65423. };
  65424. ArcFollowCamera.prototype._checkInputs = function () {
  65425. _super.prototype._checkInputs.call(this);
  65426. this.follow();
  65427. };
  65428. ArcFollowCamera.prototype.getClassName = function () {
  65429. return "ArcFollowCamera";
  65430. };
  65431. return ArcFollowCamera;
  65432. }(BABYLON.TargetCamera));
  65433. BABYLON.ArcFollowCamera = ArcFollowCamera;
  65434. })(BABYLON || (BABYLON = {}));
  65435. //# sourceMappingURL=babylon.followCamera.js.map
  65436. var BABYLON;
  65437. (function (BABYLON) {
  65438. // We're mainly based on the logic defined into the FreeCamera code
  65439. var UniversalCamera = /** @class */ (function (_super) {
  65440. __extends(UniversalCamera, _super);
  65441. //-- end properties for backward compatibility for inputs
  65442. function UniversalCamera(name, position, scene) {
  65443. var _this = _super.call(this, name, position, scene) || this;
  65444. _this.inputs.addGamepad();
  65445. return _this;
  65446. }
  65447. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  65448. //-- Begin properties for backward compatibility for inputs
  65449. get: function () {
  65450. var gamepad = this.inputs.attached["gamepad"];
  65451. if (gamepad)
  65452. return gamepad.gamepadAngularSensibility;
  65453. return 0;
  65454. },
  65455. set: function (value) {
  65456. var gamepad = this.inputs.attached["gamepad"];
  65457. if (gamepad)
  65458. gamepad.gamepadAngularSensibility = value;
  65459. },
  65460. enumerable: true,
  65461. configurable: true
  65462. });
  65463. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  65464. get: function () {
  65465. var gamepad = this.inputs.attached["gamepad"];
  65466. if (gamepad)
  65467. return gamepad.gamepadMoveSensibility;
  65468. return 0;
  65469. },
  65470. set: function (value) {
  65471. var gamepad = this.inputs.attached["gamepad"];
  65472. if (gamepad)
  65473. gamepad.gamepadMoveSensibility = value;
  65474. },
  65475. enumerable: true,
  65476. configurable: true
  65477. });
  65478. UniversalCamera.prototype.getClassName = function () {
  65479. return "UniversalCamera";
  65480. };
  65481. return UniversalCamera;
  65482. }(BABYLON.TouchCamera));
  65483. BABYLON.UniversalCamera = UniversalCamera;
  65484. })(BABYLON || (BABYLON = {}));
  65485. //# sourceMappingURL=babylon.universalCamera.js.map
  65486. var BABYLON;
  65487. (function (BABYLON) {
  65488. // We're mainly based on the logic defined into the FreeCamera code
  65489. var GamepadCamera = /** @class */ (function (_super) {
  65490. __extends(GamepadCamera, _super);
  65491. //-- end properties for backward compatibility for inputs
  65492. function GamepadCamera(name, position, scene) {
  65493. return _super.call(this, name, position, scene) || this;
  65494. }
  65495. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  65496. //-- Begin properties for backward compatibility for inputs
  65497. get: function () {
  65498. var gamepad = this.inputs.attached["gamepad"];
  65499. if (gamepad)
  65500. return gamepad.gamepadAngularSensibility;
  65501. return 0;
  65502. },
  65503. set: function (value) {
  65504. var gamepad = this.inputs.attached["gamepad"];
  65505. if (gamepad)
  65506. gamepad.gamepadAngularSensibility = value;
  65507. },
  65508. enumerable: true,
  65509. configurable: true
  65510. });
  65511. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  65512. get: function () {
  65513. var gamepad = this.inputs.attached["gamepad"];
  65514. if (gamepad)
  65515. return gamepad.gamepadMoveSensibility;
  65516. return 0;
  65517. },
  65518. set: function (value) {
  65519. var gamepad = this.inputs.attached["gamepad"];
  65520. if (gamepad)
  65521. gamepad.gamepadMoveSensibility = value;
  65522. },
  65523. enumerable: true,
  65524. configurable: true
  65525. });
  65526. GamepadCamera.prototype.getClassName = function () {
  65527. return "GamepadCamera";
  65528. };
  65529. return GamepadCamera;
  65530. }(BABYLON.UniversalCamera));
  65531. BABYLON.GamepadCamera = GamepadCamera;
  65532. })(BABYLON || (BABYLON = {}));
  65533. //# sourceMappingURL=babylon.gamepadCamera.js.map
  65534. var BABYLON;
  65535. (function (BABYLON) {
  65536. var PostProcessRenderPipelineManager = /** @class */ (function () {
  65537. function PostProcessRenderPipelineManager() {
  65538. this._renderPipelines = {};
  65539. }
  65540. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  65541. this._renderPipelines[renderPipeline._name] = renderPipeline;
  65542. };
  65543. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  65544. if (unique === void 0) { unique = false; }
  65545. var renderPipeline = this._renderPipelines[renderPipelineName];
  65546. if (!renderPipeline) {
  65547. return;
  65548. }
  65549. renderPipeline._attachCameras(cameras, unique);
  65550. };
  65551. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  65552. var renderPipeline = this._renderPipelines[renderPipelineName];
  65553. if (!renderPipeline) {
  65554. return;
  65555. }
  65556. renderPipeline._detachCameras(cameras);
  65557. };
  65558. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65559. var renderPipeline = this._renderPipelines[renderPipelineName];
  65560. if (!renderPipeline) {
  65561. return;
  65562. }
  65563. renderPipeline._enableEffect(renderEffectName, cameras);
  65564. };
  65565. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65566. var renderPipeline = this._renderPipelines[renderPipelineName];
  65567. if (!renderPipeline) {
  65568. return;
  65569. }
  65570. renderPipeline._disableEffect(renderEffectName, cameras);
  65571. };
  65572. PostProcessRenderPipelineManager.prototype.update = function () {
  65573. for (var renderPipelineName in this._renderPipelines) {
  65574. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65575. var pipeline = this._renderPipelines[renderPipelineName];
  65576. if (!pipeline.isSupported) {
  65577. pipeline.dispose();
  65578. delete this._renderPipelines[renderPipelineName];
  65579. }
  65580. else {
  65581. pipeline._update();
  65582. }
  65583. }
  65584. }
  65585. };
  65586. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  65587. for (var renderPipelineName in this._renderPipelines) {
  65588. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65589. var pipeline = this._renderPipelines[renderPipelineName];
  65590. pipeline._rebuild();
  65591. }
  65592. }
  65593. };
  65594. PostProcessRenderPipelineManager.prototype.dispose = function () {
  65595. for (var renderPipelineName in this._renderPipelines) {
  65596. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65597. var pipeline = this._renderPipelines[renderPipelineName];
  65598. pipeline.dispose();
  65599. }
  65600. }
  65601. };
  65602. return PostProcessRenderPipelineManager;
  65603. }());
  65604. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  65605. })(BABYLON || (BABYLON = {}));
  65606. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  65607. var BABYLON;
  65608. (function (BABYLON) {
  65609. /**
  65610. * This represents a set of one or more post processes in Babylon.
  65611. * A post process can be used to apply a shader to a texture after it is rendered.
  65612. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  65613. */
  65614. var PostProcessRenderEffect = /** @class */ (function () {
  65615. /**
  65616. * Instantiates a post process render effect.
  65617. * A post process can be used to apply a shader to a texture after it is rendered.
  65618. * @param engine The engine the effect is tied to
  65619. * @param name The name of the effect
  65620. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  65621. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  65622. */
  65623. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  65624. this._name = name;
  65625. this._singleInstance = singleInstance || true;
  65626. this._getPostProcesses = getPostProcesses;
  65627. this._cameras = {};
  65628. this._indicesForCamera = {};
  65629. this._postProcesses = {};
  65630. }
  65631. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  65632. /**
  65633. * Checks if all the post processes in the effect are supported.
  65634. */
  65635. get: function () {
  65636. for (var index in this._postProcesses) {
  65637. for (var ppIndex in this._postProcesses[index]) {
  65638. if (!this._postProcesses[index][ppIndex].isSupported) {
  65639. return false;
  65640. }
  65641. }
  65642. }
  65643. return true;
  65644. },
  65645. enumerable: true,
  65646. configurable: true
  65647. });
  65648. /**
  65649. * Updates the current state of the effect
  65650. */
  65651. PostProcessRenderEffect.prototype._update = function () {
  65652. };
  65653. /**
  65654. * Attaches the effect on cameras
  65655. * @param cameras The camera to attach to.
  65656. */
  65657. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  65658. var _this = this;
  65659. var cameraKey;
  65660. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65661. if (!cams) {
  65662. return;
  65663. }
  65664. for (var i = 0; i < cams.length; i++) {
  65665. var camera = cams[i];
  65666. var cameraName = camera.name;
  65667. if (this._singleInstance) {
  65668. cameraKey = 0;
  65669. }
  65670. else {
  65671. cameraKey = cameraName;
  65672. }
  65673. if (!this._postProcesses[cameraKey]) {
  65674. var postProcess = this._getPostProcesses();
  65675. if (postProcess) {
  65676. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  65677. }
  65678. }
  65679. if (!this._indicesForCamera[cameraName]) {
  65680. this._indicesForCamera[cameraName] = [];
  65681. }
  65682. this._postProcesses[cameraKey].forEach(function (postProcess) {
  65683. var index = camera.attachPostProcess(postProcess);
  65684. _this._indicesForCamera[cameraName].push(index);
  65685. });
  65686. if (!this._cameras[cameraName]) {
  65687. this._cameras[cameraName] = camera;
  65688. }
  65689. }
  65690. };
  65691. /**
  65692. * Detatches the effect on cameras
  65693. * @param cameras The camera to detatch from.
  65694. */
  65695. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  65696. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65697. if (!cams) {
  65698. return;
  65699. }
  65700. for (var i = 0; i < cams.length; i++) {
  65701. var camera = cams[i];
  65702. var cameraName = camera.name;
  65703. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65704. camera.detachPostProcess(postProcess);
  65705. });
  65706. if (this._cameras[cameraName]) {
  65707. //this._indicesForCamera.splice(index, 1);
  65708. this._cameras[cameraName] = null;
  65709. }
  65710. }
  65711. };
  65712. /**
  65713. * Enables the effect on given cameras
  65714. * @param cameras The camera to enable.
  65715. */
  65716. PostProcessRenderEffect.prototype._enable = function (cameras) {
  65717. var _this = this;
  65718. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65719. if (!cams) {
  65720. return;
  65721. }
  65722. for (var i = 0; i < cams.length; i++) {
  65723. var camera = cams[i];
  65724. var cameraName = camera.name;
  65725. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  65726. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  65727. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65728. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  65729. });
  65730. }
  65731. }
  65732. }
  65733. };
  65734. /**
  65735. * Disables the effect on the given cameras
  65736. * @param cameras The camera to disable.
  65737. */
  65738. PostProcessRenderEffect.prototype._disable = function (cameras) {
  65739. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65740. if (!cams) {
  65741. return;
  65742. }
  65743. for (var i = 0; i < cams.length; i++) {
  65744. var camera = cams[i];
  65745. var cameraName = camera.name;
  65746. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65747. camera.detachPostProcess(postProcess);
  65748. });
  65749. }
  65750. };
  65751. /**
  65752. * Gets a list of the post processes contained in the effect.
  65753. * @param camera The camera to get the post processes on.
  65754. * @returns The list of the post processes in the effect.
  65755. */
  65756. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  65757. if (this._singleInstance) {
  65758. return this._postProcesses[0];
  65759. }
  65760. else {
  65761. if (!camera) {
  65762. return null;
  65763. }
  65764. return this._postProcesses[camera.name];
  65765. }
  65766. };
  65767. return PostProcessRenderEffect;
  65768. }());
  65769. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  65770. })(BABYLON || (BABYLON = {}));
  65771. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  65772. var BABYLON;
  65773. (function (BABYLON) {
  65774. var PostProcessRenderPipeline = /** @class */ (function () {
  65775. function PostProcessRenderPipeline(engine, name) {
  65776. this._name = name;
  65777. this._renderEffects = {};
  65778. this._renderEffectsForIsolatedPass = new Array();
  65779. this._cameras = [];
  65780. }
  65781. PostProcessRenderPipeline.prototype.getClassName = function () {
  65782. return "PostProcessRenderPipeline";
  65783. };
  65784. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  65785. get: function () {
  65786. for (var renderEffectName in this._renderEffects) {
  65787. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65788. if (!this._renderEffects[renderEffectName].isSupported) {
  65789. return false;
  65790. }
  65791. }
  65792. }
  65793. return true;
  65794. },
  65795. enumerable: true,
  65796. configurable: true
  65797. });
  65798. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  65799. this._renderEffects[renderEffect._name] = renderEffect;
  65800. };
  65801. // private
  65802. PostProcessRenderPipeline.prototype._rebuild = function () {
  65803. };
  65804. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  65805. var renderEffects = this._renderEffects[renderEffectName];
  65806. if (!renderEffects) {
  65807. return;
  65808. }
  65809. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65810. };
  65811. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  65812. var renderEffects = this._renderEffects[renderEffectName];
  65813. if (!renderEffects) {
  65814. return;
  65815. }
  65816. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65817. };
  65818. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  65819. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65820. if (!cams) {
  65821. return;
  65822. }
  65823. var indicesToDelete = [];
  65824. var i;
  65825. for (i = 0; i < cams.length; i++) {
  65826. var camera = cams[i];
  65827. var cameraName = camera.name;
  65828. if (this._cameras.indexOf(camera) === -1) {
  65829. this._cameras[cameraName] = camera;
  65830. }
  65831. else if (unique) {
  65832. indicesToDelete.push(i);
  65833. }
  65834. }
  65835. for (i = 0; i < indicesToDelete.length; i++) {
  65836. cameras.splice(indicesToDelete[i], 1);
  65837. }
  65838. for (var renderEffectName in this._renderEffects) {
  65839. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65840. this._renderEffects[renderEffectName]._attachCameras(cams);
  65841. }
  65842. }
  65843. };
  65844. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  65845. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65846. if (!cams) {
  65847. return;
  65848. }
  65849. for (var renderEffectName in this._renderEffects) {
  65850. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65851. this._renderEffects[renderEffectName]._detachCameras(cams);
  65852. }
  65853. }
  65854. for (var i = 0; i < cams.length; i++) {
  65855. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  65856. }
  65857. };
  65858. PostProcessRenderPipeline.prototype._update = function () {
  65859. for (var renderEffectName in this._renderEffects) {
  65860. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65861. this._renderEffects[renderEffectName]._update();
  65862. }
  65863. }
  65864. for (var i = 0; i < this._cameras.length; i++) {
  65865. var cameraName = this._cameras[i].name;
  65866. if (this._renderEffectsForIsolatedPass[cameraName]) {
  65867. this._renderEffectsForIsolatedPass[cameraName]._update();
  65868. }
  65869. }
  65870. };
  65871. PostProcessRenderPipeline.prototype._reset = function () {
  65872. this._renderEffects = {};
  65873. this._renderEffectsForIsolatedPass = new Array();
  65874. };
  65875. PostProcessRenderPipeline.prototype.dispose = function () {
  65876. // Must be implemented by children
  65877. };
  65878. __decorate([
  65879. BABYLON.serialize()
  65880. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  65881. return PostProcessRenderPipeline;
  65882. }());
  65883. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  65884. })(BABYLON || (BABYLON = {}));
  65885. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  65886. var BABYLON;
  65887. (function (BABYLON) {
  65888. var DepthRenderer = /** @class */ (function () {
  65889. function DepthRenderer(scene, type) {
  65890. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65891. var _this = this;
  65892. this._scene = scene;
  65893. var engine = scene.getEngine();
  65894. // Render target
  65895. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  65896. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65897. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65898. this._depthMap.refreshRate = 1;
  65899. this._depthMap.renderParticles = false;
  65900. this._depthMap.renderList = null;
  65901. // set default depth value to 1.0 (far away)
  65902. this._depthMap.onClearObservable.add(function (engine) {
  65903. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  65904. });
  65905. // Custom render function
  65906. var renderSubMesh = function (subMesh) {
  65907. var mesh = subMesh.getRenderingMesh();
  65908. var scene = _this._scene;
  65909. var engine = scene.getEngine();
  65910. var material = subMesh.getMaterial();
  65911. if (!material) {
  65912. return;
  65913. }
  65914. // Culling and reverse (right handed system)
  65915. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  65916. // Managing instances
  65917. var batch = mesh._getInstancesRenderList(subMesh._id);
  65918. if (batch.mustReturn) {
  65919. return;
  65920. }
  65921. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65922. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  65923. engine.enableEffect(_this._effect);
  65924. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  65925. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65926. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  65927. // Alpha test
  65928. if (material && material.needAlphaTesting()) {
  65929. var alphaTexture = material.getAlphaTestTexture();
  65930. if (alphaTexture) {
  65931. _this._effect.setTexture("diffuseSampler", alphaTexture);
  65932. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65933. }
  65934. }
  65935. // Bones
  65936. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65937. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65938. }
  65939. // Draw
  65940. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65941. }
  65942. };
  65943. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65944. var index;
  65945. if (depthOnlySubMeshes.length) {
  65946. engine.setColorWrite(false);
  65947. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65948. renderSubMesh(depthOnlySubMeshes.data[index]);
  65949. }
  65950. engine.setColorWrite(true);
  65951. }
  65952. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65953. renderSubMesh(opaqueSubMeshes.data[index]);
  65954. }
  65955. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65956. renderSubMesh(alphaTestSubMeshes.data[index]);
  65957. }
  65958. };
  65959. }
  65960. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  65961. var material = subMesh.getMaterial();
  65962. if (material.disableDepthWrite) {
  65963. return false;
  65964. }
  65965. var defines = [];
  65966. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65967. var mesh = subMesh.getMesh();
  65968. // Alpha test
  65969. if (material && material.needAlphaTesting()) {
  65970. defines.push("#define ALPHATEST");
  65971. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65972. attribs.push(BABYLON.VertexBuffer.UVKind);
  65973. defines.push("#define UV1");
  65974. }
  65975. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65976. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65977. defines.push("#define UV2");
  65978. }
  65979. }
  65980. // Bones
  65981. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65982. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65983. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65984. if (mesh.numBoneInfluencers > 4) {
  65985. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65986. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65987. }
  65988. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65989. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  65990. }
  65991. else {
  65992. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65993. }
  65994. // Instances
  65995. if (useInstances) {
  65996. defines.push("#define INSTANCES");
  65997. attribs.push("world0");
  65998. attribs.push("world1");
  65999. attribs.push("world2");
  66000. attribs.push("world3");
  66001. }
  66002. // Get correct effect
  66003. var join = defines.join("\n");
  66004. if (this._cachedDefines !== join) {
  66005. this._cachedDefines = join;
  66006. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  66007. }
  66008. return this._effect.isReady();
  66009. };
  66010. DepthRenderer.prototype.getDepthMap = function () {
  66011. return this._depthMap;
  66012. };
  66013. // Methods
  66014. DepthRenderer.prototype.dispose = function () {
  66015. this._depthMap.dispose();
  66016. };
  66017. return DepthRenderer;
  66018. }());
  66019. BABYLON.DepthRenderer = DepthRenderer;
  66020. })(BABYLON || (BABYLON = {}));
  66021. //# sourceMappingURL=babylon.depthRenderer.js.map
  66022. var BABYLON;
  66023. (function (BABYLON) {
  66024. var SSAORenderingPipeline = /** @class */ (function (_super) {
  66025. __extends(SSAORenderingPipeline, _super);
  66026. /**
  66027. * @constructor
  66028. * @param {string} name - The rendering pipeline name
  66029. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66030. * @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 }
  66031. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66032. */
  66033. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  66034. var _this = _super.call(this, scene.getEngine(), name) || this;
  66035. // Members
  66036. /**
  66037. * The PassPostProcess id in the pipeline that contains the original scene color
  66038. * @type {string}
  66039. */
  66040. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66041. /**
  66042. * The SSAO PostProcess id in the pipeline
  66043. * @type {string}
  66044. */
  66045. _this.SSAORenderEffect = "SSAORenderEffect";
  66046. /**
  66047. * The horizontal blur PostProcess id in the pipeline
  66048. * @type {string}
  66049. */
  66050. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66051. /**
  66052. * The vertical blur PostProcess id in the pipeline
  66053. * @type {string}
  66054. */
  66055. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66056. /**
  66057. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66058. * @type {string}
  66059. */
  66060. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66061. /**
  66062. * The output strength of the SSAO post-process. Default value is 1.0.
  66063. * @type {number}
  66064. */
  66065. _this.totalStrength = 1.0;
  66066. /**
  66067. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  66068. * @type {number}
  66069. */
  66070. _this.radius = 0.0001;
  66071. /**
  66072. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  66073. * Must not be equal to fallOff and superior to fallOff.
  66074. * Default value is 0.975
  66075. * @type {number}
  66076. */
  66077. _this.area = 0.0075;
  66078. /**
  66079. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  66080. * Must not be equal to area and inferior to area.
  66081. * Default value is 0.0
  66082. * @type {number}
  66083. */
  66084. _this.fallOff = 0.000001;
  66085. /**
  66086. * The base color of the SSAO post-process
  66087. * The final result is "base + ssao" between [0, 1]
  66088. * @type {number}
  66089. */
  66090. _this.base = 0.5;
  66091. _this._firstUpdate = true;
  66092. _this._scene = scene;
  66093. // Set up assets
  66094. _this._createRandomTexture();
  66095. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66096. var ssaoRatio = ratio.ssaoRatio || ratio;
  66097. var combineRatio = ratio.combineRatio || ratio;
  66098. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66099. _this._createSSAOPostProcess(ssaoRatio);
  66100. _this._createBlurPostProcess(ssaoRatio);
  66101. _this._createSSAOCombinePostProcess(combineRatio);
  66102. // Set up pipeline
  66103. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66104. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66105. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66106. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66107. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66108. // Finish
  66109. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66110. if (cameras)
  66111. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66112. return _this;
  66113. }
  66114. // Public Methods
  66115. /**
  66116. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66117. */
  66118. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66119. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66120. for (var i = 0; i < this._scene.cameras.length; i++) {
  66121. var camera = this._scene.cameras[i];
  66122. this._originalColorPostProcess.dispose(camera);
  66123. this._ssaoPostProcess.dispose(camera);
  66124. this._blurHPostProcess.dispose(camera);
  66125. this._blurVPostProcess.dispose(camera);
  66126. this._ssaoCombinePostProcess.dispose(camera);
  66127. }
  66128. this._randomTexture.dispose();
  66129. if (disableDepthRender)
  66130. this._scene.disableDepthRenderer();
  66131. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66132. _super.prototype.dispose.call(this);
  66133. };
  66134. // Private Methods
  66135. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  66136. var _this = this;
  66137. var size = 16;
  66138. 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);
  66139. 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);
  66140. this._blurHPostProcess.onActivateObservable.add(function () {
  66141. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66142. _this._blurHPostProcess.kernel = size * dw;
  66143. });
  66144. this._blurVPostProcess.onActivateObservable.add(function () {
  66145. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66146. _this._blurVPostProcess.kernel = size * dw;
  66147. });
  66148. };
  66149. SSAORenderingPipeline.prototype._rebuild = function () {
  66150. this._firstUpdate = true;
  66151. _super.prototype._rebuild.call(this);
  66152. };
  66153. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66154. var _this = this;
  66155. var numSamples = 16;
  66156. var sampleSphere = [
  66157. 0.5381, 0.1856, -0.4319,
  66158. 0.1379, 0.2486, 0.4430,
  66159. 0.3371, 0.5679, -0.0057,
  66160. -0.6999, -0.0451, -0.0019,
  66161. 0.0689, -0.1598, -0.8547,
  66162. 0.0560, 0.0069, -0.1843,
  66163. -0.0146, 0.1402, 0.0762,
  66164. 0.0100, -0.1924, -0.0344,
  66165. -0.3577, -0.5301, -0.4358,
  66166. -0.3169, 0.1063, 0.0158,
  66167. 0.0103, -0.5869, 0.0046,
  66168. -0.0897, -0.4940, 0.3287,
  66169. 0.7119, -0.0154, -0.0918,
  66170. -0.0533, 0.0596, -0.5411,
  66171. 0.0352, -0.0631, 0.5460,
  66172. -0.4776, 0.2847, -0.0271
  66173. ];
  66174. var samplesFactor = 1.0 / numSamples;
  66175. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  66176. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66177. "area", "fallOff", "base", "range", "viewport"
  66178. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66179. this._ssaoPostProcess.onApply = function (effect) {
  66180. if (_this._firstUpdate) {
  66181. effect.setArray3("sampleSphere", sampleSphere);
  66182. effect.setFloat("samplesFactor", samplesFactor);
  66183. effect.setFloat("randTextureTiles", 4.0);
  66184. }
  66185. effect.setFloat("totalStrength", _this.totalStrength);
  66186. effect.setFloat("radius", _this.radius);
  66187. effect.setFloat("area", _this.area);
  66188. effect.setFloat("fallOff", _this.fallOff);
  66189. effect.setFloat("base", _this.base);
  66190. effect.setTexture("textureSampler", _this._depthTexture);
  66191. effect.setTexture("randomSampler", _this._randomTexture);
  66192. };
  66193. };
  66194. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66195. var _this = this;
  66196. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66197. this._ssaoCombinePostProcess.onApply = function (effect) {
  66198. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66199. };
  66200. };
  66201. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  66202. var size = 512;
  66203. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66204. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66205. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66206. var context = this._randomTexture.getContext();
  66207. var rand = function (min, max) {
  66208. return Math.random() * (max - min) + min;
  66209. };
  66210. var randVector = BABYLON.Vector3.Zero();
  66211. for (var x = 0; x < size; x++) {
  66212. for (var y = 0; y < size; y++) {
  66213. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  66214. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  66215. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  66216. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66217. context.fillRect(x, y, 1, 1);
  66218. }
  66219. }
  66220. this._randomTexture.update(false);
  66221. };
  66222. __decorate([
  66223. BABYLON.serialize()
  66224. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  66225. __decorate([
  66226. BABYLON.serialize()
  66227. ], SSAORenderingPipeline.prototype, "radius", void 0);
  66228. __decorate([
  66229. BABYLON.serialize()
  66230. ], SSAORenderingPipeline.prototype, "area", void 0);
  66231. __decorate([
  66232. BABYLON.serialize()
  66233. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  66234. __decorate([
  66235. BABYLON.serialize()
  66236. ], SSAORenderingPipeline.prototype, "base", void 0);
  66237. return SSAORenderingPipeline;
  66238. }(BABYLON.PostProcessRenderPipeline));
  66239. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  66240. })(BABYLON || (BABYLON = {}));
  66241. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  66242. var BABYLON;
  66243. (function (BABYLON) {
  66244. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  66245. __extends(SSAO2RenderingPipeline, _super);
  66246. /**
  66247. * @constructor
  66248. * @param {string} name - The rendering pipeline name
  66249. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66250. * @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 }
  66251. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66252. */
  66253. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  66254. var _this = _super.call(this, scene.getEngine(), name) || this;
  66255. // Members
  66256. /**
  66257. * The PassPostProcess id in the pipeline that contains the original scene color
  66258. * @type {string}
  66259. */
  66260. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66261. /**
  66262. * The SSAO PostProcess id in the pipeline
  66263. * @type {string}
  66264. */
  66265. _this.SSAORenderEffect = "SSAORenderEffect";
  66266. /**
  66267. * The horizontal blur PostProcess id in the pipeline
  66268. * @type {string}
  66269. */
  66270. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66271. /**
  66272. * The vertical blur PostProcess id in the pipeline
  66273. * @type {string}
  66274. */
  66275. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66276. /**
  66277. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66278. * @type {string}
  66279. */
  66280. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66281. /**
  66282. * The output strength of the SSAO post-process. Default value is 1.0.
  66283. * @type {number}
  66284. */
  66285. _this.totalStrength = 1.0;
  66286. /**
  66287. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  66288. * @type {number}
  66289. */
  66290. _this.maxZ = 100.0;
  66291. /**
  66292. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  66293. * @type {number}
  66294. */
  66295. _this.minZAspect = 0.2;
  66296. /**
  66297. * Number of samples used for the SSAO calculations. Default value is 8
  66298. * @type {number}
  66299. */
  66300. _this._samples = 8;
  66301. /**
  66302. * Are we using bilateral blur ?
  66303. * @type {boolean}
  66304. */
  66305. _this._expensiveBlur = true;
  66306. /**
  66307. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  66308. * @type {number}
  66309. */
  66310. _this.radius = 2.0;
  66311. /**
  66312. * The base color of the SSAO post-process
  66313. * The final result is "base + ssao" between [0, 1]
  66314. * @type {number}
  66315. */
  66316. _this.base = 0.1;
  66317. _this._firstUpdate = true;
  66318. _this._scene = scene;
  66319. if (!_this.isSupported) {
  66320. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  66321. return _this;
  66322. }
  66323. var ssaoRatio = ratio.ssaoRatio || ratio;
  66324. var blurRatio = ratio.blurRatio || ratio;
  66325. // Set up assets
  66326. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  66327. _this._createRandomTexture();
  66328. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  66329. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  66330. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66331. _this._createSSAOPostProcess(1.0);
  66332. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  66333. _this._createSSAOCombinePostProcess(blurRatio);
  66334. // Set up pipeline
  66335. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66336. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66337. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66338. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66339. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66340. // Finish
  66341. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66342. if (cameras)
  66343. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66344. return _this;
  66345. }
  66346. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  66347. get: function () {
  66348. return this._samples;
  66349. },
  66350. set: function (n) {
  66351. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  66352. this._samples = n;
  66353. this._sampleSphere = this._generateHemisphere();
  66354. this._firstUpdate = true;
  66355. },
  66356. enumerable: true,
  66357. configurable: true
  66358. });
  66359. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  66360. get: function () {
  66361. return this._expensiveBlur;
  66362. },
  66363. set: function (b) {
  66364. 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"]);
  66365. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  66366. this._expensiveBlur = b;
  66367. this._firstUpdate = true;
  66368. },
  66369. enumerable: true,
  66370. configurable: true
  66371. });
  66372. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  66373. /**
  66374. * Support test.
  66375. * @type {boolean}
  66376. */
  66377. get: function () {
  66378. var engine = BABYLON.Engine.LastCreatedEngine;
  66379. if (!engine) {
  66380. return false;
  66381. }
  66382. return engine.getCaps().drawBuffersExtension;
  66383. },
  66384. enumerable: true,
  66385. configurable: true
  66386. });
  66387. // Public Methods
  66388. /**
  66389. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66390. */
  66391. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  66392. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  66393. for (var i = 0; i < this._scene.cameras.length; i++) {
  66394. var camera = this._scene.cameras[i];
  66395. this._originalColorPostProcess.dispose(camera);
  66396. this._ssaoPostProcess.dispose(camera);
  66397. this._blurHPostProcess.dispose(camera);
  66398. this._blurVPostProcess.dispose(camera);
  66399. this._ssaoCombinePostProcess.dispose(camera);
  66400. }
  66401. this._randomTexture.dispose();
  66402. if (disableGeometryBufferRenderer)
  66403. this._scene.disableGeometryBufferRenderer();
  66404. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66405. _super.prototype.dispose.call(this);
  66406. };
  66407. // Private Methods
  66408. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  66409. var _this = this;
  66410. this._samplerOffsets = [];
  66411. var expensive = this.expensiveBlur;
  66412. for (var i = -8; i < 8; i++) {
  66413. this._samplerOffsets.push(i * 2 + 0.5);
  66414. }
  66415. 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");
  66416. this._blurHPostProcess.onApply = function (effect) {
  66417. if (!_this._scene.activeCamera) {
  66418. return;
  66419. }
  66420. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  66421. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66422. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66423. effect.setFloat("radius", _this.radius);
  66424. effect.setTexture("depthSampler", _this._depthTexture);
  66425. if (_this._firstUpdate) {
  66426. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66427. }
  66428. };
  66429. 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");
  66430. this._blurVPostProcess.onApply = function (effect) {
  66431. if (!_this._scene.activeCamera) {
  66432. return;
  66433. }
  66434. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  66435. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66436. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66437. effect.setFloat("radius", _this.radius);
  66438. effect.setTexture("depthSampler", _this._depthTexture);
  66439. if (_this._firstUpdate) {
  66440. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66441. _this._firstUpdate = false;
  66442. }
  66443. };
  66444. };
  66445. SSAO2RenderingPipeline.prototype._rebuild = function () {
  66446. this._firstUpdate = true;
  66447. _super.prototype._rebuild.call(this);
  66448. };
  66449. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  66450. var numSamples = this.samples;
  66451. var result = [];
  66452. var vector, scale;
  66453. var rand = function (min, max) {
  66454. return Math.random() * (max - min) + min;
  66455. };
  66456. var i = 0;
  66457. while (i < numSamples) {
  66458. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  66459. vector.normalize();
  66460. scale = i / numSamples;
  66461. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  66462. vector.scaleInPlace(scale);
  66463. result.push(vector.x, vector.y, vector.z);
  66464. i++;
  66465. }
  66466. return result;
  66467. };
  66468. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66469. var _this = this;
  66470. var numSamples = this.samples;
  66471. this._sampleSphere = this._generateHemisphere();
  66472. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  66473. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66474. "base", "range", "projection", "near", "far", "texelSize",
  66475. "xViewport", "yViewport", "maxZ", "minZAspect"
  66476. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66477. this._ssaoPostProcess.onApply = function (effect) {
  66478. if (_this._firstUpdate) {
  66479. effect.setArray3("sampleSphere", _this._sampleSphere);
  66480. effect.setFloat("randTextureTiles", 4.0);
  66481. }
  66482. if (!_this._scene.activeCamera) {
  66483. return;
  66484. }
  66485. effect.setFloat("samplesFactor", 1 / _this.samples);
  66486. effect.setFloat("totalStrength", _this.totalStrength);
  66487. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  66488. effect.setFloat("radius", _this.radius);
  66489. effect.setFloat("maxZ", _this.maxZ);
  66490. effect.setFloat("minZAspect", _this.minZAspect);
  66491. effect.setFloat("base", _this.base);
  66492. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66493. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66494. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  66495. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  66496. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  66497. effect.setTexture("textureSampler", _this._depthTexture);
  66498. effect.setTexture("normalSampler", _this._normalTexture);
  66499. effect.setTexture("randomSampler", _this._randomTexture);
  66500. };
  66501. };
  66502. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66503. var _this = this;
  66504. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66505. this._ssaoCombinePostProcess.onApply = function (effect) {
  66506. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66507. };
  66508. };
  66509. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  66510. var size = 512;
  66511. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66512. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66513. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66514. var context = this._randomTexture.getContext();
  66515. var rand = function (min, max) {
  66516. return Math.random() * (max - min) + min;
  66517. };
  66518. var randVector = BABYLON.Vector3.Zero();
  66519. for (var x = 0; x < size; x++) {
  66520. for (var y = 0; y < size; y++) {
  66521. randVector.x = rand(0.0, 1.0);
  66522. randVector.y = rand(0.0, 1.0);
  66523. randVector.z = 0.0;
  66524. randVector.normalize();
  66525. randVector.scaleInPlace(255);
  66526. randVector.x = Math.floor(randVector.x);
  66527. randVector.y = Math.floor(randVector.y);
  66528. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66529. context.fillRect(x, y, 1, 1);
  66530. }
  66531. }
  66532. this._randomTexture.update(false);
  66533. };
  66534. __decorate([
  66535. BABYLON.serialize()
  66536. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  66537. __decorate([
  66538. BABYLON.serialize()
  66539. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  66540. __decorate([
  66541. BABYLON.serialize()
  66542. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  66543. __decorate([
  66544. BABYLON.serialize("samples")
  66545. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  66546. __decorate([
  66547. BABYLON.serialize("expensiveBlur")
  66548. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  66549. __decorate([
  66550. BABYLON.serialize()
  66551. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  66552. __decorate([
  66553. BABYLON.serialize()
  66554. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  66555. return SSAO2RenderingPipeline;
  66556. }(BABYLON.PostProcessRenderPipeline));
  66557. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  66558. })(BABYLON || (BABYLON = {}));
  66559. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  66560. // BABYLON.JS Chromatic Aberration GLSL Shader
  66561. // Author: Olivier Guyot
  66562. // Separates very slightly R, G and B colors on the edges of the screen
  66563. // Inspired by Francois Tarlier & Martins Upitis
  66564. var BABYLON;
  66565. (function (BABYLON) {
  66566. var LensRenderingPipeline = /** @class */ (function (_super) {
  66567. __extends(LensRenderingPipeline, _super);
  66568. /**
  66569. * @constructor
  66570. *
  66571. * Effect parameters are as follow:
  66572. * {
  66573. * chromatic_aberration: number; // from 0 to x (1 for realism)
  66574. * edge_blur: number; // from 0 to x (1 for realism)
  66575. * distortion: number; // from 0 to x (1 for realism)
  66576. * grain_amount: number; // from 0 to 1
  66577. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  66578. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  66579. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  66580. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  66581. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  66582. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  66583. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  66584. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  66585. * }
  66586. * Note: if an effect parameter is unset, effect is disabled
  66587. *
  66588. * @param {string} name - The rendering pipeline name
  66589. * @param {object} parameters - An object containing all parameters (see above)
  66590. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66591. * @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)
  66592. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66593. */
  66594. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  66595. if (ratio === void 0) { ratio = 1.0; }
  66596. var _this = _super.call(this, scene.getEngine(), name) || this;
  66597. // Lens effects can be of the following:
  66598. // - chromatic aberration (slight shift of RGB colors)
  66599. // - blur on the edge of the lens
  66600. // - lens distortion
  66601. // - depth-of-field blur & highlights enhancing
  66602. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  66603. // - grain effect (noise or custom texture)
  66604. // Two additional texture samplers are needed:
  66605. // - depth map (for depth-of-field)
  66606. // - grain texture
  66607. /**
  66608. * The chromatic aberration PostProcess id in the pipeline
  66609. * @type {string}
  66610. */
  66611. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  66612. /**
  66613. * The highlights enhancing PostProcess id in the pipeline
  66614. * @type {string}
  66615. */
  66616. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  66617. /**
  66618. * The depth-of-field PostProcess id in the pipeline
  66619. * @type {string}
  66620. */
  66621. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  66622. _this._scene = scene;
  66623. // Fetch texture samplers
  66624. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66625. if (parameters.grain_texture) {
  66626. _this._grainTexture = parameters.grain_texture;
  66627. }
  66628. else {
  66629. _this._createGrainTexture();
  66630. }
  66631. // save parameters
  66632. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  66633. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  66634. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  66635. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  66636. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  66637. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  66638. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  66639. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  66640. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  66641. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  66642. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  66643. // Create effects
  66644. _this._createChromaticAberrationPostProcess(ratio);
  66645. _this._createHighlightsPostProcess(ratio);
  66646. _this._createDepthOfFieldPostProcess(ratio / 4);
  66647. // Set up pipeline
  66648. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  66649. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  66650. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  66651. if (_this._highlightsGain === -1) {
  66652. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  66653. }
  66654. // Finish
  66655. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66656. if (cameras) {
  66657. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66658. }
  66659. return _this;
  66660. }
  66661. // public methods (self explanatory)
  66662. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  66663. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  66664. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  66665. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  66666. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  66667. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  66668. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  66669. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  66670. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  66671. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  66672. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  66673. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  66674. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  66675. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  66676. };
  66677. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  66678. this._highlightsPostProcess.updateEffect();
  66679. };
  66680. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  66681. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  66682. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  66683. this._highlightsGain = amount;
  66684. };
  66685. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  66686. if (this._highlightsGain === -1) {
  66687. this._highlightsGain = 1.0;
  66688. }
  66689. this._highlightsThreshold = amount;
  66690. };
  66691. LensRenderingPipeline.prototype.disableHighlights = function () {
  66692. this._highlightsGain = -1;
  66693. };
  66694. /**
  66695. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  66696. */
  66697. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66698. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66699. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66700. this._chromaticAberrationPostProcess = null;
  66701. this._highlightsPostProcess = null;
  66702. this._depthOfFieldPostProcess = null;
  66703. this._grainTexture.dispose();
  66704. if (disableDepthRender)
  66705. this._scene.disableDepthRenderer();
  66706. };
  66707. // colors shifting and distortion
  66708. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  66709. var _this = this;
  66710. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  66711. [], // samplers
  66712. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66713. this._chromaticAberrationPostProcess.onApply = function (effect) {
  66714. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  66715. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66716. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66717. };
  66718. };
  66719. // highlights enhancing
  66720. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  66721. var _this = this;
  66722. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  66723. [], // samplers
  66724. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  66725. this._highlightsPostProcess.onApply = function (effect) {
  66726. effect.setFloat('gain', _this._highlightsGain);
  66727. effect.setFloat('threshold', _this._highlightsThreshold);
  66728. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  66729. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66730. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66731. };
  66732. };
  66733. // colors shifting and distortion
  66734. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  66735. var _this = this;
  66736. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  66737. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  66738. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  66739. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66740. this._depthOfFieldPostProcess.onApply = function (effect) {
  66741. effect.setTexture("depthSampler", _this._depthTexture);
  66742. effect.setTexture("grainSampler", _this._grainTexture);
  66743. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  66744. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  66745. effect.setFloat('grain_amount', _this._grainAmount);
  66746. effect.setBool('blur_noise', _this._blurNoise);
  66747. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66748. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66749. effect.setFloat('distortion', _this._distortion);
  66750. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  66751. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  66752. effect.setFloat('aperture', _this._dofAperture);
  66753. effect.setFloat('darken', _this._dofDarken);
  66754. effect.setFloat('edge_blur', _this._edgeBlur);
  66755. effect.setBool('highlights', (_this._highlightsGain !== -1));
  66756. if (_this._scene.activeCamera) {
  66757. effect.setFloat('near', _this._scene.activeCamera.minZ);
  66758. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  66759. }
  66760. };
  66761. };
  66762. // creates a black and white random noise texture, 512x512
  66763. LensRenderingPipeline.prototype._createGrainTexture = function () {
  66764. var size = 512;
  66765. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66766. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66767. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66768. var context = this._grainTexture.getContext();
  66769. var rand = function (min, max) {
  66770. return Math.random() * (max - min) + min;
  66771. };
  66772. var value;
  66773. for (var x = 0; x < size; x++) {
  66774. for (var y = 0; y < size; y++) {
  66775. value = Math.floor(rand(0.42, 0.58) * 255);
  66776. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  66777. context.fillRect(x, y, 1, 1);
  66778. }
  66779. }
  66780. this._grainTexture.update(false);
  66781. };
  66782. return LensRenderingPipeline;
  66783. }(BABYLON.PostProcessRenderPipeline));
  66784. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  66785. })(BABYLON || (BABYLON = {}));
  66786. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  66787. var BABYLON;
  66788. (function (BABYLON) {
  66789. var StandardRenderingPipeline = /** @class */ (function (_super) {
  66790. __extends(StandardRenderingPipeline, _super);
  66791. /**
  66792. * @constructor
  66793. * @param {string} name - The rendering pipeline name
  66794. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66795. * @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)
  66796. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  66797. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66798. */
  66799. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  66800. if (originalPostProcess === void 0) { originalPostProcess = null; }
  66801. var _this = _super.call(this, scene.getEngine(), name) || this;
  66802. _this.downSampleX4PostProcess = null;
  66803. _this.brightPassPostProcess = null;
  66804. _this.blurHPostProcesses = [];
  66805. _this.blurVPostProcesses = [];
  66806. _this.textureAdderPostProcess = null;
  66807. _this.volumetricLightPostProcess = null;
  66808. _this.volumetricLightSmoothXPostProcess = null;
  66809. _this.volumetricLightSmoothYPostProcess = null;
  66810. _this.volumetricLightMergePostProces = null;
  66811. _this.volumetricLightFinalPostProcess = null;
  66812. _this.luminancePostProcess = null;
  66813. _this.luminanceDownSamplePostProcesses = [];
  66814. _this.hdrPostProcess = null;
  66815. _this.textureAdderFinalPostProcess = null;
  66816. _this.lensFlareFinalPostProcess = null;
  66817. _this.hdrFinalPostProcess = null;
  66818. _this.lensFlarePostProcess = null;
  66819. _this.lensFlareComposePostProcess = null;
  66820. _this.motionBlurPostProcess = null;
  66821. _this.depthOfFieldPostProcess = null;
  66822. // Values
  66823. _this.brightThreshold = 1.0;
  66824. _this.blurWidth = 512.0;
  66825. _this.horizontalBlur = false;
  66826. _this.exposure = 1.0;
  66827. _this.lensTexture = null;
  66828. _this.volumetricLightCoefficient = 0.2;
  66829. _this.volumetricLightPower = 4.0;
  66830. _this.volumetricLightBlurScale = 64.0;
  66831. _this.sourceLight = null;
  66832. _this.hdrMinimumLuminance = 1.0;
  66833. _this.hdrDecreaseRate = 0.5;
  66834. _this.hdrIncreaseRate = 0.5;
  66835. _this.lensColorTexture = null;
  66836. _this.lensFlareStrength = 20.0;
  66837. _this.lensFlareGhostDispersal = 1.4;
  66838. _this.lensFlareHaloWidth = 0.7;
  66839. _this.lensFlareDistortionStrength = 16.0;
  66840. _this.lensStarTexture = null;
  66841. _this.lensFlareDirtTexture = null;
  66842. _this.depthOfFieldDistance = 10.0;
  66843. _this.depthOfFieldBlurWidth = 64.0;
  66844. _this.motionStrength = 1.0;
  66845. // IAnimatable
  66846. _this.animations = [];
  66847. _this._currentDepthOfFieldSource = null;
  66848. _this._hdrCurrentLuminance = 1.0;
  66849. // Getters and setters
  66850. _this._bloomEnabled = true;
  66851. _this._depthOfFieldEnabled = false;
  66852. _this._vlsEnabled = false;
  66853. _this._lensFlareEnabled = false;
  66854. _this._hdrEnabled = false;
  66855. _this._motionBlurEnabled = false;
  66856. _this._motionBlurSamples = 64.0;
  66857. _this._volumetricLightStepsCount = 50.0;
  66858. _this._cameras = cameras || [];
  66859. // Initialize
  66860. _this._scene = scene;
  66861. _this._basePostProcess = originalPostProcess;
  66862. _this._ratio = ratio;
  66863. // Misc
  66864. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66865. // Finish
  66866. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66867. _this._buildPipeline();
  66868. return _this;
  66869. }
  66870. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  66871. get: function () {
  66872. return this._bloomEnabled;
  66873. },
  66874. set: function (enabled) {
  66875. if (this._bloomEnabled === enabled) {
  66876. return;
  66877. }
  66878. this._bloomEnabled = enabled;
  66879. this._buildPipeline();
  66880. },
  66881. enumerable: true,
  66882. configurable: true
  66883. });
  66884. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  66885. get: function () {
  66886. return this._depthOfFieldEnabled;
  66887. },
  66888. set: function (enabled) {
  66889. if (this._depthOfFieldEnabled === enabled) {
  66890. return;
  66891. }
  66892. this._depthOfFieldEnabled = enabled;
  66893. this._buildPipeline();
  66894. },
  66895. enumerable: true,
  66896. configurable: true
  66897. });
  66898. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  66899. get: function () {
  66900. return this._lensFlareEnabled;
  66901. },
  66902. set: function (enabled) {
  66903. if (this._lensFlareEnabled === enabled) {
  66904. return;
  66905. }
  66906. this._lensFlareEnabled = enabled;
  66907. this._buildPipeline();
  66908. },
  66909. enumerable: true,
  66910. configurable: true
  66911. });
  66912. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  66913. get: function () {
  66914. return this._hdrEnabled;
  66915. },
  66916. set: function (enabled) {
  66917. if (this._hdrEnabled === enabled) {
  66918. return;
  66919. }
  66920. this._hdrEnabled = enabled;
  66921. this._buildPipeline();
  66922. },
  66923. enumerable: true,
  66924. configurable: true
  66925. });
  66926. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  66927. get: function () {
  66928. return this._vlsEnabled;
  66929. },
  66930. set: function (enabled) {
  66931. if (this._vlsEnabled === enabled) {
  66932. return;
  66933. }
  66934. if (enabled) {
  66935. var geometry = this._scene.enableGeometryBufferRenderer();
  66936. if (!geometry) {
  66937. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  66938. return;
  66939. }
  66940. }
  66941. this._vlsEnabled = enabled;
  66942. this._buildPipeline();
  66943. },
  66944. enumerable: true,
  66945. configurable: true
  66946. });
  66947. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  66948. get: function () {
  66949. return this._motionBlurEnabled;
  66950. },
  66951. set: function (enabled) {
  66952. if (this._motionBlurEnabled === enabled) {
  66953. return;
  66954. }
  66955. this._motionBlurEnabled = enabled;
  66956. this._buildPipeline();
  66957. },
  66958. enumerable: true,
  66959. configurable: true
  66960. });
  66961. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  66962. get: function () {
  66963. return this._volumetricLightStepsCount;
  66964. },
  66965. set: function (count) {
  66966. if (this.volumetricLightPostProcess) {
  66967. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  66968. }
  66969. this._volumetricLightStepsCount = count;
  66970. },
  66971. enumerable: true,
  66972. configurable: true
  66973. });
  66974. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  66975. get: function () {
  66976. return this._motionBlurSamples;
  66977. },
  66978. set: function (samples) {
  66979. if (this.motionBlurPostProcess) {
  66980. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  66981. }
  66982. this._motionBlurSamples = samples;
  66983. },
  66984. enumerable: true,
  66985. configurable: true
  66986. });
  66987. StandardRenderingPipeline.prototype._buildPipeline = function () {
  66988. var _this = this;
  66989. var ratio = this._ratio;
  66990. var scene = this._scene;
  66991. this._disposePostProcesses();
  66992. this._reset();
  66993. // Create pass post-process
  66994. if (!this._basePostProcess) {
  66995. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  66996. this.originalPostProcess.onApply = function (effect) {
  66997. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  66998. };
  66999. }
  67000. else {
  67001. this.originalPostProcess = this._basePostProcess;
  67002. }
  67003. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  67004. this._currentDepthOfFieldSource = this.originalPostProcess;
  67005. if (this._vlsEnabled) {
  67006. // Create volumetric light
  67007. this._createVolumetricLightPostProcess(scene, ratio);
  67008. // Create volumetric light final post-process
  67009. 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);
  67010. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  67011. }
  67012. if (this._bloomEnabled) {
  67013. // Create down sample X4 post-process
  67014. this._createDownSampleX4PostProcess(scene, ratio / 2);
  67015. // Create bright pass post-process
  67016. this._createBrightPassPostProcess(scene, ratio / 2);
  67017. // Create gaussian blur post-processes (down sampling blurs)
  67018. this._createBlurPostProcesses(scene, ratio / 4, 1);
  67019. // Create texture adder post-process
  67020. this._createTextureAdderPostProcess(scene, ratio);
  67021. // Create depth-of-field source post-process
  67022. 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);
  67023. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  67024. }
  67025. if (this._lensFlareEnabled) {
  67026. // Create lens flare post-process
  67027. this._createLensFlarePostProcess(scene, ratio);
  67028. // Create depth-of-field source post-process post lens-flare and disable it now
  67029. 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);
  67030. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  67031. }
  67032. if (this._hdrEnabled) {
  67033. // Create luminance
  67034. this._createLuminancePostProcesses(scene, this._floatTextureType);
  67035. // Create HDR
  67036. this._createHdrPostProcess(scene, ratio);
  67037. // Create depth-of-field source post-process post hdr and disable it now
  67038. 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);
  67039. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  67040. }
  67041. if (this._depthOfFieldEnabled) {
  67042. // Create gaussian blur used by depth-of-field
  67043. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  67044. // Create depth-of-field post-process
  67045. this._createDepthOfFieldPostProcess(scene, ratio);
  67046. }
  67047. if (this._motionBlurEnabled) {
  67048. // Create motion blur post-process
  67049. this._createMotionBlurPostProcess(scene, ratio);
  67050. }
  67051. if (this._cameras !== null) {
  67052. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67053. }
  67054. };
  67055. // Down Sample X4 Post-Processs
  67056. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  67057. var _this = this;
  67058. var downSampleX4Offsets = new Array(32);
  67059. 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);
  67060. this.downSampleX4PostProcess.onApply = function (effect) {
  67061. var id = 0;
  67062. var width = _this.downSampleX4PostProcess.width;
  67063. var height = _this.downSampleX4PostProcess.height;
  67064. for (var i = -2; i < 2; i++) {
  67065. for (var j = -2; j < 2; j++) {
  67066. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  67067. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  67068. id += 2;
  67069. }
  67070. }
  67071. effect.setArray2("dsOffsets", downSampleX4Offsets);
  67072. };
  67073. // Add to pipeline
  67074. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  67075. };
  67076. // Brightpass Post-Process
  67077. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  67078. var _this = this;
  67079. var brightOffsets = new Array(8);
  67080. 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);
  67081. this.brightPassPostProcess.onApply = function (effect) {
  67082. var sU = (1.0 / _this.brightPassPostProcess.width);
  67083. var sV = (1.0 / _this.brightPassPostProcess.height);
  67084. brightOffsets[0] = -0.5 * sU;
  67085. brightOffsets[1] = 0.5 * sV;
  67086. brightOffsets[2] = 0.5 * sU;
  67087. brightOffsets[3] = 0.5 * sV;
  67088. brightOffsets[4] = -0.5 * sU;
  67089. brightOffsets[5] = -0.5 * sV;
  67090. brightOffsets[6] = 0.5 * sU;
  67091. brightOffsets[7] = -0.5 * sV;
  67092. effect.setArray2("dsOffsets", brightOffsets);
  67093. effect.setFloat("brightThreshold", _this.brightThreshold);
  67094. };
  67095. // Add to pipeline
  67096. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  67097. };
  67098. // Create blur H&V post-processes
  67099. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  67100. var _this = this;
  67101. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  67102. var engine = scene.getEngine();
  67103. 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);
  67104. 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);
  67105. blurX.onActivateObservable.add(function () {
  67106. var dw = blurX.width / engine.getRenderWidth();
  67107. blurX.kernel = _this[blurWidthKey] * dw;
  67108. });
  67109. blurY.onActivateObservable.add(function () {
  67110. var dw = blurY.height / engine.getRenderHeight();
  67111. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  67112. });
  67113. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  67114. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  67115. this.blurHPostProcesses.push(blurX);
  67116. this.blurVPostProcesses.push(blurY);
  67117. };
  67118. // Create texture adder post-process
  67119. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  67120. var _this = this;
  67121. 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);
  67122. this.textureAdderPostProcess.onApply = function (effect) {
  67123. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  67124. effect.setTexture("lensSampler", _this.lensTexture);
  67125. effect.setFloat("exposure", _this.exposure);
  67126. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  67127. };
  67128. // Add to pipeline
  67129. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  67130. };
  67131. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  67132. var _this = this;
  67133. var geometryRenderer = scene.enableGeometryBufferRenderer();
  67134. geometryRenderer.enablePosition = true;
  67135. var geometry = geometryRenderer.getGBuffer();
  67136. // Base post-process
  67137. 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));
  67138. var depthValues = BABYLON.Vector2.Zero();
  67139. this.volumetricLightPostProcess.onApply = function (effect) {
  67140. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67141. var generator = _this.sourceLight.getShadowGenerator();
  67142. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67143. effect.setTexture("positionSampler", geometry.textures[2]);
  67144. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67145. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67146. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67147. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67148. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67149. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67150. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67151. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67152. effect.setVector2("depthValues", depthValues);
  67153. }
  67154. };
  67155. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67156. // Smooth
  67157. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67158. // Merge
  67159. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  67160. this.volumetricLightMergePostProces.onApply = function (effect) {
  67161. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  67162. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  67163. };
  67164. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  67165. };
  67166. // Create luminance
  67167. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  67168. var _this = this;
  67169. // Create luminance
  67170. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  67171. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  67172. var offsets = [];
  67173. this.luminancePostProcess.onApply = function (effect) {
  67174. var sU = (1.0 / _this.luminancePostProcess.width);
  67175. var sV = (1.0 / _this.luminancePostProcess.height);
  67176. offsets[0] = -0.5 * sU;
  67177. offsets[1] = 0.5 * sV;
  67178. offsets[2] = 0.5 * sU;
  67179. offsets[3] = 0.5 * sV;
  67180. offsets[4] = -0.5 * sU;
  67181. offsets[5] = -0.5 * sV;
  67182. offsets[6] = 0.5 * sU;
  67183. offsets[7] = -0.5 * sV;
  67184. effect.setArray2("lumOffsets", offsets);
  67185. };
  67186. // Add to pipeline
  67187. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  67188. // Create down sample luminance
  67189. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  67190. var size = Math.pow(3, i);
  67191. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  67192. if (i === 0) {
  67193. defines += "#define FINAL_DOWN_SAMPLER";
  67194. }
  67195. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  67196. this.luminanceDownSamplePostProcesses.push(postProcess);
  67197. }
  67198. // Create callbacks and add effects
  67199. var lastLuminance = this.luminancePostProcess;
  67200. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  67201. var downSampleOffsets = new Array(18);
  67202. pp.onApply = function (effect) {
  67203. if (!lastLuminance) {
  67204. return;
  67205. }
  67206. var id = 0;
  67207. for (var x = -1; x < 2; x++) {
  67208. for (var y = -1; y < 2; y++) {
  67209. downSampleOffsets[id] = x / lastLuminance.width;
  67210. downSampleOffsets[id + 1] = y / lastLuminance.height;
  67211. id += 2;
  67212. }
  67213. }
  67214. effect.setArray2("dsOffsets", downSampleOffsets);
  67215. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  67216. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67217. lastLuminance = _this.luminancePostProcess;
  67218. }
  67219. else {
  67220. lastLuminance = pp;
  67221. }
  67222. };
  67223. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67224. pp.onAfterRender = function (effect) {
  67225. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  67226. 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);
  67227. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  67228. };
  67229. }
  67230. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  67231. });
  67232. };
  67233. // Create HDR post-process
  67234. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  67235. var _this = this;
  67236. 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);
  67237. var outputLiminance = 1;
  67238. var time = 0;
  67239. var lastTime = 0;
  67240. this.hdrPostProcess.onApply = function (effect) {
  67241. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  67242. time += scene.getEngine().getDeltaTime();
  67243. if (outputLiminance < 0) {
  67244. outputLiminance = _this._hdrCurrentLuminance;
  67245. }
  67246. else {
  67247. var dt = (lastTime - time) / 1000.0;
  67248. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  67249. outputLiminance += _this.hdrDecreaseRate * dt;
  67250. }
  67251. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  67252. outputLiminance -= _this.hdrIncreaseRate * dt;
  67253. }
  67254. else {
  67255. outputLiminance = _this._hdrCurrentLuminance;
  67256. }
  67257. }
  67258. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  67259. effect.setFloat("averageLuminance", outputLiminance);
  67260. lastTime = time;
  67261. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  67262. };
  67263. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  67264. };
  67265. // Create lens flare post-process
  67266. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  67267. var _this = this;
  67268. 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);
  67269. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  67270. this._createBlurPostProcesses(scene, ratio / 4, 2);
  67271. 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);
  67272. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  67273. var resolution = new BABYLON.Vector2(0, 0);
  67274. // Lens flare
  67275. this.lensFlarePostProcess.onApply = function (effect) {
  67276. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  67277. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  67278. effect.setFloat("strength", _this.lensFlareStrength);
  67279. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  67280. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  67281. // Shift
  67282. resolution.x = _this.lensFlarePostProcess.width;
  67283. resolution.y = _this.lensFlarePostProcess.height;
  67284. effect.setVector2("resolution", resolution);
  67285. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  67286. };
  67287. // Compose
  67288. 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);
  67289. 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);
  67290. this.lensFlareComposePostProcess.onApply = function (effect) {
  67291. if (!_this._scene.activeCamera) {
  67292. return;
  67293. }
  67294. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67295. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  67296. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  67297. // Lens start rotation matrix
  67298. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  67299. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  67300. 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));
  67301. camRot *= 4.0;
  67302. 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);
  67303. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  67304. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  67305. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  67306. };
  67307. };
  67308. // Create depth-of-field post-process
  67309. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  67310. var _this = this;
  67311. 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);
  67312. this.depthOfFieldPostProcess.onApply = function (effect) {
  67313. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67314. effect.setTexture("depthSampler", _this._getDepthTexture());
  67315. effect.setFloat("distance", _this.depthOfFieldDistance);
  67316. };
  67317. // Add to pipeline
  67318. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  67319. };
  67320. // Create motion blur post-process
  67321. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  67322. var _this = this;
  67323. 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);
  67324. var motionScale = 0;
  67325. var prevViewProjection = BABYLON.Matrix.Identity();
  67326. var invViewProjection = BABYLON.Matrix.Identity();
  67327. var viewProjection = BABYLON.Matrix.Identity();
  67328. var screenSize = BABYLON.Vector2.Zero();
  67329. this.motionBlurPostProcess.onApply = function (effect) {
  67330. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  67331. viewProjection.invertToRef(invViewProjection);
  67332. effect.setMatrix("inverseViewProjection", invViewProjection);
  67333. effect.setMatrix("prevViewProjection", prevViewProjection);
  67334. prevViewProjection = viewProjection;
  67335. screenSize.x = _this.motionBlurPostProcess.width;
  67336. screenSize.y = _this.motionBlurPostProcess.height;
  67337. effect.setVector2("screenSize", screenSize);
  67338. motionScale = scene.getEngine().getFps() / 60.0;
  67339. effect.setFloat("motionScale", motionScale);
  67340. effect.setFloat("motionStrength", _this.motionStrength);
  67341. effect.setTexture("depthSampler", _this._getDepthTexture());
  67342. };
  67343. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  67344. };
  67345. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  67346. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  67347. var renderer = this._scene.enableGeometryBufferRenderer();
  67348. return renderer.getGBuffer().textures[0];
  67349. }
  67350. return this._scene.enableDepthRenderer().getDepthMap();
  67351. };
  67352. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  67353. for (var i = 0; i < this._cameras.length; i++) {
  67354. var camera = this._cameras[i];
  67355. if (this.originalPostProcess) {
  67356. this.originalPostProcess.dispose(camera);
  67357. }
  67358. if (this.downSampleX4PostProcess) {
  67359. this.downSampleX4PostProcess.dispose(camera);
  67360. }
  67361. if (this.brightPassPostProcess) {
  67362. this.brightPassPostProcess.dispose(camera);
  67363. }
  67364. if (this.textureAdderPostProcess) {
  67365. this.textureAdderPostProcess.dispose(camera);
  67366. }
  67367. if (this.textureAdderFinalPostProcess) {
  67368. this.textureAdderFinalPostProcess.dispose(camera);
  67369. }
  67370. if (this.volumetricLightPostProcess) {
  67371. this.volumetricLightPostProcess.dispose(camera);
  67372. }
  67373. if (this.volumetricLightSmoothXPostProcess) {
  67374. this.volumetricLightSmoothXPostProcess.dispose(camera);
  67375. }
  67376. if (this.volumetricLightSmoothYPostProcess) {
  67377. this.volumetricLightSmoothYPostProcess.dispose(camera);
  67378. }
  67379. if (this.volumetricLightMergePostProces) {
  67380. this.volumetricLightMergePostProces.dispose(camera);
  67381. }
  67382. if (this.volumetricLightFinalPostProcess) {
  67383. this.volumetricLightFinalPostProcess.dispose(camera);
  67384. }
  67385. if (this.lensFlarePostProcess) {
  67386. this.lensFlarePostProcess.dispose(camera);
  67387. }
  67388. if (this.lensFlareComposePostProcess) {
  67389. this.lensFlareComposePostProcess.dispose(camera);
  67390. }
  67391. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  67392. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  67393. }
  67394. if (this.luminancePostProcess) {
  67395. this.luminancePostProcess.dispose(camera);
  67396. }
  67397. if (this.hdrPostProcess) {
  67398. this.hdrPostProcess.dispose(camera);
  67399. }
  67400. if (this.hdrFinalPostProcess) {
  67401. this.hdrFinalPostProcess.dispose(camera);
  67402. }
  67403. if (this.depthOfFieldPostProcess) {
  67404. this.depthOfFieldPostProcess.dispose(camera);
  67405. }
  67406. if (this.motionBlurPostProcess) {
  67407. this.motionBlurPostProcess.dispose(camera);
  67408. }
  67409. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  67410. this.blurHPostProcesses[j].dispose(camera);
  67411. }
  67412. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  67413. this.blurVPostProcesses[j].dispose(camera);
  67414. }
  67415. }
  67416. this.originalPostProcess = null;
  67417. this.downSampleX4PostProcess = null;
  67418. this.brightPassPostProcess = null;
  67419. this.textureAdderPostProcess = null;
  67420. this.textureAdderFinalPostProcess = null;
  67421. this.volumetricLightPostProcess = null;
  67422. this.volumetricLightSmoothXPostProcess = null;
  67423. this.volumetricLightSmoothYPostProcess = null;
  67424. this.volumetricLightMergePostProces = null;
  67425. this.volumetricLightFinalPostProcess = null;
  67426. this.lensFlarePostProcess = null;
  67427. this.lensFlareComposePostProcess = null;
  67428. this.luminancePostProcess = null;
  67429. this.hdrPostProcess = null;
  67430. this.hdrFinalPostProcess = null;
  67431. this.depthOfFieldPostProcess = null;
  67432. this.motionBlurPostProcess = null;
  67433. this.luminanceDownSamplePostProcesses = [];
  67434. this.blurHPostProcesses = [];
  67435. this.blurVPostProcesses = [];
  67436. };
  67437. // Dispose
  67438. StandardRenderingPipeline.prototype.dispose = function () {
  67439. this._disposePostProcesses();
  67440. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67441. _super.prototype.dispose.call(this);
  67442. };
  67443. // Serialize rendering pipeline
  67444. StandardRenderingPipeline.prototype.serialize = function () {
  67445. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67446. serializationObject.customType = "StandardRenderingPipeline";
  67447. return serializationObject;
  67448. };
  67449. /**
  67450. * Static members
  67451. */
  67452. // Parse serialized pipeline
  67453. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67454. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  67455. };
  67456. // Luminance steps
  67457. StandardRenderingPipeline.LuminanceSteps = 6;
  67458. __decorate([
  67459. BABYLON.serialize()
  67460. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  67461. __decorate([
  67462. BABYLON.serialize()
  67463. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  67464. __decorate([
  67465. BABYLON.serialize()
  67466. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  67467. __decorate([
  67468. BABYLON.serialize()
  67469. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  67470. __decorate([
  67471. BABYLON.serializeAsTexture("lensTexture")
  67472. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  67473. __decorate([
  67474. BABYLON.serialize()
  67475. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  67476. __decorate([
  67477. BABYLON.serialize()
  67478. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  67479. __decorate([
  67480. BABYLON.serialize()
  67481. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  67482. __decorate([
  67483. BABYLON.serialize()
  67484. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  67485. __decorate([
  67486. BABYLON.serialize()
  67487. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  67488. __decorate([
  67489. BABYLON.serialize()
  67490. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  67491. __decorate([
  67492. BABYLON.serializeAsTexture("lensColorTexture")
  67493. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  67494. __decorate([
  67495. BABYLON.serialize()
  67496. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  67497. __decorate([
  67498. BABYLON.serialize()
  67499. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  67500. __decorate([
  67501. BABYLON.serialize()
  67502. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  67503. __decorate([
  67504. BABYLON.serialize()
  67505. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  67506. __decorate([
  67507. BABYLON.serializeAsTexture("lensStarTexture")
  67508. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  67509. __decorate([
  67510. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  67511. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  67512. __decorate([
  67513. BABYLON.serialize()
  67514. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  67515. __decorate([
  67516. BABYLON.serialize()
  67517. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  67518. __decorate([
  67519. BABYLON.serialize()
  67520. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  67521. __decorate([
  67522. BABYLON.serialize()
  67523. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  67524. __decorate([
  67525. BABYLON.serialize()
  67526. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  67527. __decorate([
  67528. BABYLON.serialize()
  67529. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  67530. __decorate([
  67531. BABYLON.serialize()
  67532. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  67533. __decorate([
  67534. BABYLON.serialize()
  67535. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  67536. __decorate([
  67537. BABYLON.serialize()
  67538. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  67539. __decorate([
  67540. BABYLON.serialize()
  67541. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  67542. __decorate([
  67543. BABYLON.serialize()
  67544. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  67545. __decorate([
  67546. BABYLON.serialize()
  67547. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  67548. return StandardRenderingPipeline;
  67549. }(BABYLON.PostProcessRenderPipeline));
  67550. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  67551. })(BABYLON || (BABYLON = {}));
  67552. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  67553. var BABYLON;
  67554. (function (BABYLON) {
  67555. var FxaaPostProcess = /** @class */ (function (_super) {
  67556. __extends(FxaaPostProcess, _super);
  67557. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67558. if (camera === void 0) { camera = null; }
  67559. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67560. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  67561. _this.onApplyObservable.add(function (effect) {
  67562. var texelSize = _this.texelSize;
  67563. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  67564. });
  67565. return _this;
  67566. }
  67567. return FxaaPostProcess;
  67568. }(BABYLON.PostProcess));
  67569. BABYLON.FxaaPostProcess = FxaaPostProcess;
  67570. })(BABYLON || (BABYLON = {}));
  67571. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  67572. var BABYLON;
  67573. (function (BABYLON) {
  67574. /**
  67575. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  67576. */
  67577. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  67578. __extends(CircleOfConfusionPostProcess, _super);
  67579. /**
  67580. * Creates a new instance of @see CircleOfConfusionPostProcess
  67581. * @param name The name of the effect.
  67582. * @param scene The scene the effect belongs to.
  67583. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  67584. * @param options The required width/height ratio to downsize to before computing the render pass.
  67585. * @param camera The camera to apply the render pass to.
  67586. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67587. * @param engine The engine which the post process will be applied. (default: current engine)
  67588. * @param reusable If the post process can be reused on the same frame. (default: false)
  67589. * @param textureType Type of textures used when performing the post process. (default: 0)
  67590. */
  67591. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  67592. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67593. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67594. /**
  67595. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  67596. */
  67597. _this.lensSize = 50;
  67598. /**
  67599. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67600. */
  67601. _this.fStop = 1.4;
  67602. /**
  67603. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67604. */
  67605. _this.focusDistance = 2000;
  67606. /**
  67607. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  67608. */
  67609. _this.focalLength = 50;
  67610. _this.onApplyObservable.add(function (effect) {
  67611. effect.setTexture("depthSampler", depthTexture);
  67612. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  67613. var aperture = _this.lensSize / _this.fStop;
  67614. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  67615. effect.setFloat('focusDistance', _this.focusDistance);
  67616. effect.setFloat('cocPrecalculation', cocPrecalculation);
  67617. if (scene.activeCamera) {
  67618. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  67619. }
  67620. });
  67621. return _this;
  67622. }
  67623. return CircleOfConfusionPostProcess;
  67624. }(BABYLON.PostProcess));
  67625. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  67626. })(BABYLON || (BABYLON = {}));
  67627. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  67628. var BABYLON;
  67629. (function (BABYLON) {
  67630. /**
  67631. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  67632. */
  67633. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  67634. __extends(DepthOfFieldMergePostProcess, _super);
  67635. /**
  67636. * Creates a new instance of @see CircleOfConfusionPostProcess
  67637. * @param name The name of the effect.
  67638. * @param original The non-blurred image to be modified
  67639. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  67640. * @param blurSteps Incrimental bluring post processes.
  67641. * @param options The required width/height ratio to downsize to before computing the render pass.
  67642. * @param camera The camera to apply the render pass to.
  67643. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67644. * @param engine The engine which the post process will be applied. (default: current engine)
  67645. * @param reusable If the post process can be reused on the same frame. (default: false)
  67646. * @param textureType Type of textures used when performing the post process. (default: 0)
  67647. */
  67648. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  67649. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67650. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  67651. _this.onApplyObservable.add(function (effect) {
  67652. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  67653. effect.setTextureFromPostProcess("originalSampler", original);
  67654. blurSteps.forEach(function (step, index) {
  67655. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  67656. });
  67657. });
  67658. return _this;
  67659. }
  67660. return DepthOfFieldMergePostProcess;
  67661. }(BABYLON.PostProcess));
  67662. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  67663. })(BABYLON || (BABYLON = {}));
  67664. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  67665. var BABYLON;
  67666. (function (BABYLON) {
  67667. /**
  67668. * Specifies the level of max blur that should be applied when using the depth of field effect
  67669. */
  67670. var DepthOfFieldEffectBlurLevel;
  67671. (function (DepthOfFieldEffectBlurLevel) {
  67672. /**
  67673. * Subtle blur
  67674. */
  67675. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  67676. /**
  67677. * Medium blur
  67678. */
  67679. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  67680. /**
  67681. * Large blur
  67682. */
  67683. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  67684. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  67685. ;
  67686. /**
  67687. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  67688. */
  67689. var DepthOfFieldEffect = /** @class */ (function (_super) {
  67690. __extends(DepthOfFieldEffect, _super);
  67691. /**
  67692. * Creates a new instance of @see DepthOfFieldEffect
  67693. * @param scene The scene the effect belongs to.
  67694. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  67695. */
  67696. function DepthOfFieldEffect(scene, blurLevel, pipelineTextureType) {
  67697. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  67698. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  67699. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  67700. // Enable and get current depth map
  67701. var depthMap = scene.enableDepthRenderer().getDepthMap();
  67702. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  67703. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67704. // Capture circle of confusion texture
  67705. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67706. _this._depthOfFieldPass.autoClear = false;
  67707. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  67708. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  67709. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  67710. _this._depthOfFieldBlurY = [];
  67711. _this._depthOfFieldBlurX = [];
  67712. var blurCount = 1;
  67713. var kernelSize = 15;
  67714. switch (blurLevel) {
  67715. case DepthOfFieldEffectBlurLevel.High: {
  67716. blurCount = 3;
  67717. kernelSize = 51;
  67718. break;
  67719. }
  67720. case DepthOfFieldEffectBlurLevel.Medium: {
  67721. blurCount = 2;
  67722. kernelSize = 31;
  67723. break;
  67724. }
  67725. default: {
  67726. kernelSize = 15;
  67727. blurCount = 1;
  67728. break;
  67729. }
  67730. }
  67731. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  67732. for (var i = 0; i < blurCount; i++) {
  67733. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67734. blurY.autoClear = false;
  67735. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67736. blurX.autoClear = false;
  67737. _this._depthOfFieldBlurY.push(blurY);
  67738. _this._depthOfFieldBlurX.push(blurX);
  67739. }
  67740. // Merge blurred images with original image based on circleOfConfusion
  67741. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67742. _this._depthOfFieldMerge.autoClear = false;
  67743. // Set all post processes on the effect.
  67744. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  67745. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  67746. effects.push(_this._depthOfFieldBlurY[i]);
  67747. effects.push(_this._depthOfFieldBlurX[i]);
  67748. }
  67749. effects.push(_this._depthOfFieldMerge);
  67750. return effects;
  67751. }, true) || this;
  67752. return _this;
  67753. }
  67754. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  67755. get: function () {
  67756. return this._circleOfConfusion.focalLength;
  67757. },
  67758. /**
  67759. * The focal the length of the camera used in the effect
  67760. */
  67761. set: function (value) {
  67762. this._circleOfConfusion.focalLength = value;
  67763. },
  67764. enumerable: true,
  67765. configurable: true
  67766. });
  67767. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  67768. get: function () {
  67769. return this._circleOfConfusion.fStop;
  67770. },
  67771. /**
  67772. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67773. */
  67774. set: function (value) {
  67775. this._circleOfConfusion.fStop = value;
  67776. },
  67777. enumerable: true,
  67778. configurable: true
  67779. });
  67780. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  67781. get: function () {
  67782. return this._circleOfConfusion.focusDistance;
  67783. },
  67784. /**
  67785. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67786. */
  67787. set: function (value) {
  67788. this._circleOfConfusion.focusDistance = value;
  67789. },
  67790. enumerable: true,
  67791. configurable: true
  67792. });
  67793. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  67794. get: function () {
  67795. return this._circleOfConfusion.lensSize;
  67796. },
  67797. /**
  67798. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  67799. */
  67800. set: function (value) {
  67801. this._circleOfConfusion.lensSize = value;
  67802. },
  67803. enumerable: true,
  67804. configurable: true
  67805. });
  67806. /**
  67807. * Disposes each of the internal effects for a given camera.
  67808. * @param camera The camera to dispose the effect on.
  67809. */
  67810. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  67811. this._depthOfFieldPass.dispose(camera);
  67812. this._circleOfConfusion.dispose(camera);
  67813. this._depthOfFieldBlurX.forEach(function (element) {
  67814. element.dispose(camera);
  67815. });
  67816. this._depthOfFieldBlurY.forEach(function (element) {
  67817. element.dispose(camera);
  67818. });
  67819. this._depthOfFieldMerge.dispose(camera);
  67820. };
  67821. return DepthOfFieldEffect;
  67822. }(BABYLON.PostProcessRenderEffect));
  67823. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  67824. })(BABYLON || (BABYLON = {}));
  67825. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  67826. var BABYLON;
  67827. (function (BABYLON) {
  67828. /**
  67829. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  67830. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  67831. */
  67832. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  67833. __extends(DefaultRenderingPipeline, _super);
  67834. /**
  67835. * @constructor
  67836. * @param {string} name - The rendering pipeline name
  67837. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67838. * @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)
  67839. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67840. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  67841. */
  67842. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  67843. if (automaticBuild === void 0) { automaticBuild = true; }
  67844. var _this = _super.call(this, scene.getEngine(), name) || this;
  67845. /**
  67846. * ID of the pass post process used for bloom,
  67847. */
  67848. _this.PassPostProcessId = "PassPostProcessEffect";
  67849. /**
  67850. * ID of the highlight post process used for bloom,
  67851. */
  67852. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  67853. /**
  67854. * ID of the blurX post process used for bloom,
  67855. */
  67856. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  67857. /**
  67858. * ID of the blurY post process used for bloom,
  67859. */
  67860. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  67861. /**
  67862. * ID of the copy back post process used for bloom,
  67863. */
  67864. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  67865. /**
  67866. * ID of the image processing post process;
  67867. */
  67868. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  67869. /**
  67870. * ID of the Fast Approximate Anti-Aliasing post process;
  67871. */
  67872. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  67873. /**
  67874. * ID of the final merge post process;
  67875. */
  67876. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  67877. /**
  67878. * Animations which can be used to tweak settings over a period of time
  67879. */
  67880. _this.animations = [];
  67881. // Values
  67882. _this._bloomEnabled = false;
  67883. _this._depthOfFieldEnabled = false;
  67884. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  67885. _this._fxaaEnabled = false;
  67886. _this._imageProcessingEnabled = true;
  67887. _this._bloomScale = 0.6;
  67888. _this._buildAllowed = true;
  67889. /**
  67890. * Specifies the size of the bloom blur kernel, relative to the final output size
  67891. */
  67892. _this.bloomKernel = 64;
  67893. /**
  67894. * Specifies the weight of the bloom in the final rendering
  67895. */
  67896. _this._bloomWeight = 0.15;
  67897. _this._cameras = cameras || [];
  67898. _this._buildAllowed = automaticBuild;
  67899. // Initialize
  67900. _this._scene = scene;
  67901. var caps = _this._scene.getEngine().getCaps();
  67902. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  67903. // Misc
  67904. if (_this._hdr) {
  67905. if (caps.textureHalfFloatRender) {
  67906. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67907. }
  67908. else if (caps.textureFloatRender) {
  67909. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67910. }
  67911. }
  67912. else {
  67913. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67914. }
  67915. // Attach
  67916. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67917. _this._buildPipeline();
  67918. return _this;
  67919. }
  67920. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  67921. get: function () {
  67922. return this._bloomWeight;
  67923. },
  67924. /**
  67925. * The strength of the bloom.
  67926. */
  67927. set: function (value) {
  67928. if (this._bloomWeight === value) {
  67929. return;
  67930. }
  67931. this._bloomWeight = value;
  67932. if (this._hdr && this.copyBack) {
  67933. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  67934. }
  67935. },
  67936. enumerable: true,
  67937. configurable: true
  67938. });
  67939. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  67940. get: function () {
  67941. return this._bloomScale;
  67942. },
  67943. /**
  67944. * The scale of the bloom, lower value will provide better performance.
  67945. */
  67946. set: function (value) {
  67947. if (this._bloomScale === value) {
  67948. return;
  67949. }
  67950. this._bloomScale = value;
  67951. this._buildPipeline();
  67952. },
  67953. enumerable: true,
  67954. configurable: true
  67955. });
  67956. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  67957. get: function () {
  67958. return this._bloomEnabled;
  67959. },
  67960. /**
  67961. * Enable or disable the bloom from the pipeline
  67962. */
  67963. set: function (enabled) {
  67964. if (this._bloomEnabled === enabled) {
  67965. return;
  67966. }
  67967. this._bloomEnabled = enabled;
  67968. this._buildPipeline();
  67969. },
  67970. enumerable: true,
  67971. configurable: true
  67972. });
  67973. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  67974. /**
  67975. * If the depth of field is enabled.
  67976. */
  67977. get: function () {
  67978. return this._depthOfFieldEnabled;
  67979. },
  67980. set: function (enabled) {
  67981. if (this._depthOfFieldEnabled === enabled) {
  67982. return;
  67983. }
  67984. this._depthOfFieldEnabled = enabled;
  67985. this._buildPipeline();
  67986. },
  67987. enumerable: true,
  67988. configurable: true
  67989. });
  67990. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  67991. /**
  67992. * Blur level of the depth of field effect. (Higher blur will effect performance)
  67993. */
  67994. get: function () {
  67995. return this._depthOfFieldBlurLevel;
  67996. },
  67997. set: function (value) {
  67998. if (this._depthOfFieldBlurLevel === value) {
  67999. return;
  68000. }
  68001. this._depthOfFieldBlurLevel = value;
  68002. this._buildPipeline();
  68003. },
  68004. enumerable: true,
  68005. configurable: true
  68006. });
  68007. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  68008. get: function () {
  68009. return this._fxaaEnabled;
  68010. },
  68011. /**
  68012. * If the anti aliasing is enabled.
  68013. */
  68014. set: function (enabled) {
  68015. if (this._fxaaEnabled === enabled) {
  68016. return;
  68017. }
  68018. this._fxaaEnabled = enabled;
  68019. this._buildPipeline();
  68020. },
  68021. enumerable: true,
  68022. configurable: true
  68023. });
  68024. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  68025. get: function () {
  68026. return this._imageProcessingEnabled;
  68027. },
  68028. /**
  68029. * If image processing is enabled.
  68030. */
  68031. set: function (enabled) {
  68032. if (this._imageProcessingEnabled === enabled) {
  68033. return;
  68034. }
  68035. this._imageProcessingEnabled = enabled;
  68036. this._buildPipeline();
  68037. },
  68038. enumerable: true,
  68039. configurable: true
  68040. });
  68041. /**
  68042. * Force the compilation of the entire pipeline.
  68043. */
  68044. DefaultRenderingPipeline.prototype.prepare = function () {
  68045. var previousState = this._buildAllowed;
  68046. this._buildAllowed = true;
  68047. this._buildPipeline();
  68048. this._buildAllowed = previousState;
  68049. };
  68050. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  68051. var _this = this;
  68052. if (!this._buildAllowed) {
  68053. return;
  68054. }
  68055. var engine = this._scene.getEngine();
  68056. this._disposePostProcesses();
  68057. this._reset();
  68058. if (this.depthOfFieldEnabled) {
  68059. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  68060. this.addEffect(this.depthOfField);
  68061. }
  68062. if (this.bloomEnabled) {
  68063. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68064. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  68065. if (!this._hdr) {
  68066. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68067. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  68068. this.highlights.autoClear = false;
  68069. this.highlights.alwaysForcePOT = true;
  68070. }
  68071. 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);
  68072. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  68073. this.blurX.alwaysForcePOT = true;
  68074. this.blurX.autoClear = false;
  68075. this.blurX.onActivateObservable.add(function () {
  68076. var dw = _this.blurX.width / engine.getRenderWidth(true);
  68077. _this.blurX.kernel = _this.bloomKernel * dw;
  68078. });
  68079. 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);
  68080. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  68081. this.blurY.alwaysForcePOT = true;
  68082. this.blurY.autoClear = false;
  68083. this.blurY.onActivateObservable.add(function () {
  68084. var dh = _this.blurY.height / engine.getRenderHeight(true);
  68085. _this.blurY.kernel = _this.bloomKernel * dh;
  68086. });
  68087. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68088. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  68089. this.copyBack.alwaysForcePOT = true;
  68090. if (this._hdr) {
  68091. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  68092. var w = this.bloomWeight;
  68093. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  68094. }
  68095. else {
  68096. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  68097. }
  68098. this.copyBack.autoClear = false;
  68099. }
  68100. if (this._imageProcessingEnabled) {
  68101. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68102. if (this._hdr) {
  68103. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  68104. }
  68105. else {
  68106. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  68107. }
  68108. }
  68109. if (this.fxaaEnabled) {
  68110. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68111. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  68112. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68113. }
  68114. else if (this._hdr && this.imageProcessing) {
  68115. this.finalMerge = this.imageProcessing;
  68116. }
  68117. else {
  68118. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68119. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  68120. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68121. }
  68122. if (this.bloomEnabled) {
  68123. if (this._hdr) {
  68124. this.copyBack.shareOutputWith(this.blurX);
  68125. if (this.imageProcessing) {
  68126. this.imageProcessing.shareOutputWith(this.pass);
  68127. this.imageProcessing.autoClear = false;
  68128. }
  68129. else if (this.fxaa) {
  68130. this.fxaa.shareOutputWith(this.pass);
  68131. }
  68132. else {
  68133. this.finalMerge.shareOutputWith(this.pass);
  68134. }
  68135. }
  68136. else {
  68137. if (this.fxaa) {
  68138. this.fxaa.shareOutputWith(this.pass);
  68139. }
  68140. else {
  68141. this.finalMerge.shareOutputWith(this.pass);
  68142. }
  68143. }
  68144. }
  68145. if (this._cameras !== null) {
  68146. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68147. }
  68148. };
  68149. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  68150. for (var i = 0; i < this._cameras.length; i++) {
  68151. var camera = this._cameras[i];
  68152. if (this.pass) {
  68153. this.pass.dispose(camera);
  68154. }
  68155. if (this.highlights) {
  68156. this.highlights.dispose(camera);
  68157. }
  68158. if (this.blurX) {
  68159. this.blurX.dispose(camera);
  68160. }
  68161. if (this.blurY) {
  68162. this.blurY.dispose(camera);
  68163. }
  68164. if (this.copyBack) {
  68165. this.copyBack.dispose(camera);
  68166. }
  68167. if (this.imageProcessing) {
  68168. this.imageProcessing.dispose(camera);
  68169. }
  68170. if (this.fxaa) {
  68171. this.fxaa.dispose(camera);
  68172. }
  68173. if (this.finalMerge) {
  68174. this.finalMerge.dispose(camera);
  68175. }
  68176. if (this.depthOfField) {
  68177. this.depthOfField.disposeEffects(camera);
  68178. }
  68179. }
  68180. this.pass = null;
  68181. this.highlights = null;
  68182. this.blurX = null;
  68183. this.blurY = null;
  68184. this.copyBack = null;
  68185. this.imageProcessing = null;
  68186. this.fxaa = null;
  68187. this.finalMerge = null;
  68188. this.depthOfField = null;
  68189. };
  68190. /**
  68191. * Dispose of the pipeline and stop all post processes
  68192. */
  68193. DefaultRenderingPipeline.prototype.dispose = function () {
  68194. this._disposePostProcesses();
  68195. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68196. _super.prototype.dispose.call(this);
  68197. };
  68198. /**
  68199. * Serialize the rendering pipeline (Used when exporting)
  68200. * @returns the serialized object
  68201. */
  68202. DefaultRenderingPipeline.prototype.serialize = function () {
  68203. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68204. serializationObject.customType = "DefaultRenderingPipeline";
  68205. return serializationObject;
  68206. };
  68207. /**
  68208. * Parse the serialized pipeline
  68209. * @param source Source pipeline.
  68210. * @param scene The scene to load the pipeline to.
  68211. * @param rootUrl The URL of the serialized pipeline.
  68212. * @returns An instantiated pipeline from the serialized object.
  68213. */
  68214. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68215. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  68216. };
  68217. __decorate([
  68218. BABYLON.serialize()
  68219. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  68220. __decorate([
  68221. BABYLON.serialize()
  68222. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  68223. __decorate([
  68224. BABYLON.serialize()
  68225. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  68226. __decorate([
  68227. BABYLON.serialize()
  68228. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  68229. __decorate([
  68230. BABYLON.serialize()
  68231. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  68232. __decorate([
  68233. BABYLON.serialize()
  68234. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  68235. __decorate([
  68236. BABYLON.serialize()
  68237. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  68238. __decorate([
  68239. BABYLON.serialize()
  68240. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  68241. __decorate([
  68242. BABYLON.serialize()
  68243. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  68244. __decorate([
  68245. BABYLON.serialize()
  68246. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  68247. return DefaultRenderingPipeline;
  68248. }(BABYLON.PostProcessRenderPipeline));
  68249. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  68250. })(BABYLON || (BABYLON = {}));
  68251. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  68252. var BABYLON;
  68253. (function (BABYLON) {
  68254. /**
  68255. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  68256. */
  68257. var GeometryBufferRenderer = /** @class */ (function () {
  68258. /**
  68259. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  68260. * @param scene The scene the buffer belongs to
  68261. * @param ratio How big is the buffer related to the main canvas.
  68262. */
  68263. function GeometryBufferRenderer(scene, ratio) {
  68264. if (ratio === void 0) { ratio = 1; }
  68265. this._enablePosition = false;
  68266. this._scene = scene;
  68267. this._ratio = ratio;
  68268. // Render target
  68269. this._createRenderTargets();
  68270. }
  68271. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  68272. /**
  68273. * Set the render list (meshes to be rendered) used in the G buffer.
  68274. */
  68275. set: function (meshes) {
  68276. this._multiRenderTarget.renderList = meshes;
  68277. },
  68278. enumerable: true,
  68279. configurable: true
  68280. });
  68281. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  68282. /**
  68283. * Gets wether or not G buffer are supported by the running hardware.
  68284. * This requires draw buffer supports
  68285. */
  68286. get: function () {
  68287. return this._multiRenderTarget.isSupported;
  68288. },
  68289. enumerable: true,
  68290. configurable: true
  68291. });
  68292. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  68293. /**
  68294. * Gets wether or not position are enabled for the G buffer.
  68295. */
  68296. get: function () {
  68297. return this._enablePosition;
  68298. },
  68299. /**
  68300. * Sets wether or not position are enabled for the G buffer.
  68301. */
  68302. set: function (enable) {
  68303. this._enablePosition = enable;
  68304. this.dispose();
  68305. this._createRenderTargets();
  68306. },
  68307. enumerable: true,
  68308. configurable: true
  68309. });
  68310. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  68311. /**
  68312. * Gets the scene associated with the buffer.
  68313. */
  68314. get: function () {
  68315. return this._scene;
  68316. },
  68317. enumerable: true,
  68318. configurable: true
  68319. });
  68320. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  68321. /**
  68322. * Gets the ratio used by the buffer during its creation.
  68323. * How big is the buffer related to the main canvas.
  68324. */
  68325. get: function () {
  68326. return this._ratio;
  68327. },
  68328. enumerable: true,
  68329. configurable: true
  68330. });
  68331. /**
  68332. * Checks wether everything is ready to render a submesh to the G buffer.
  68333. * @param subMesh the submesh to check readiness for
  68334. * @param useInstances is the mesh drawn using instance or not
  68335. * @returns true if ready otherwise false
  68336. */
  68337. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  68338. var material = subMesh.getMaterial();
  68339. if (material && material.disableDepthWrite) {
  68340. return false;
  68341. }
  68342. var defines = [];
  68343. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  68344. var mesh = subMesh.getMesh();
  68345. // Alpha test
  68346. if (material && material.needAlphaTesting()) {
  68347. defines.push("#define ALPHATEST");
  68348. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68349. attribs.push(BABYLON.VertexBuffer.UVKind);
  68350. defines.push("#define UV1");
  68351. }
  68352. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68353. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68354. defines.push("#define UV2");
  68355. }
  68356. }
  68357. // Buffers
  68358. if (this._enablePosition) {
  68359. defines.push("#define POSITION");
  68360. }
  68361. // Bones
  68362. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68363. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68364. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68365. if (mesh.numBoneInfluencers > 4) {
  68366. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68367. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68368. }
  68369. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68370. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68371. }
  68372. else {
  68373. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68374. }
  68375. // Instances
  68376. if (useInstances) {
  68377. defines.push("#define INSTANCES");
  68378. attribs.push("world0");
  68379. attribs.push("world1");
  68380. attribs.push("world2");
  68381. attribs.push("world3");
  68382. }
  68383. // Get correct effect
  68384. var join = defines.join("\n");
  68385. if (this._cachedDefines !== join) {
  68386. this._cachedDefines = join;
  68387. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  68388. }
  68389. return this._effect.isReady();
  68390. };
  68391. /**
  68392. * Gets the current underlying G Buffer.
  68393. * @returns the buffer
  68394. */
  68395. GeometryBufferRenderer.prototype.getGBuffer = function () {
  68396. return this._multiRenderTarget;
  68397. };
  68398. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  68399. /**
  68400. * Gets the number of samples used to render the buffer (anti aliasing).
  68401. */
  68402. get: function () {
  68403. return this._multiRenderTarget.samples;
  68404. },
  68405. /**
  68406. * Sets the number of samples used to render the buffer (anti aliasing).
  68407. */
  68408. set: function (value) {
  68409. this._multiRenderTarget.samples = value;
  68410. },
  68411. enumerable: true,
  68412. configurable: true
  68413. });
  68414. /**
  68415. * Disposes the renderer and frees up associated resources.
  68416. */
  68417. GeometryBufferRenderer.prototype.dispose = function () {
  68418. this.getGBuffer().dispose();
  68419. };
  68420. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  68421. var _this = this;
  68422. var engine = this._scene.getEngine();
  68423. var count = this._enablePosition ? 3 : 2;
  68424. 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 });
  68425. if (!this.isSupported) {
  68426. return;
  68427. }
  68428. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68429. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68430. this._multiRenderTarget.refreshRate = 1;
  68431. this._multiRenderTarget.renderParticles = false;
  68432. this._multiRenderTarget.renderList = null;
  68433. // set default depth value to 1.0 (far away)
  68434. this._multiRenderTarget.onClearObservable.add(function (engine) {
  68435. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  68436. });
  68437. // Custom render function
  68438. var renderSubMesh = function (subMesh) {
  68439. var mesh = subMesh.getRenderingMesh();
  68440. var scene = _this._scene;
  68441. var engine = scene.getEngine();
  68442. var material = subMesh.getMaterial();
  68443. if (!material) {
  68444. return;
  68445. }
  68446. // Culling
  68447. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68448. // Managing instances
  68449. var batch = mesh._getInstancesRenderList(subMesh._id);
  68450. if (batch.mustReturn) {
  68451. return;
  68452. }
  68453. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68454. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  68455. engine.enableEffect(_this._effect);
  68456. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68457. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68458. _this._effect.setMatrix("view", scene.getViewMatrix());
  68459. // Alpha test
  68460. if (material && material.needAlphaTesting()) {
  68461. var alphaTexture = material.getAlphaTestTexture();
  68462. if (alphaTexture) {
  68463. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68464. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68465. }
  68466. }
  68467. // Bones
  68468. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68469. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68470. }
  68471. // Draw
  68472. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68473. }
  68474. };
  68475. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68476. var index;
  68477. if (depthOnlySubMeshes.length) {
  68478. engine.setColorWrite(false);
  68479. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68480. renderSubMesh(depthOnlySubMeshes.data[index]);
  68481. }
  68482. engine.setColorWrite(true);
  68483. }
  68484. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68485. renderSubMesh(opaqueSubMeshes.data[index]);
  68486. }
  68487. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68488. renderSubMesh(alphaTestSubMeshes.data[index]);
  68489. }
  68490. };
  68491. };
  68492. return GeometryBufferRenderer;
  68493. }());
  68494. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  68495. })(BABYLON || (BABYLON = {}));
  68496. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  68497. var BABYLON;
  68498. (function (BABYLON) {
  68499. var RefractionPostProcess = /** @class */ (function (_super) {
  68500. __extends(RefractionPostProcess, _super);
  68501. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  68502. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  68503. _this.color = color;
  68504. _this.depth = depth;
  68505. _this.colorLevel = colorLevel;
  68506. _this._ownRefractionTexture = true;
  68507. _this.onActivateObservable.add(function (cam) {
  68508. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  68509. });
  68510. _this.onApplyObservable.add(function (effect) {
  68511. effect.setColor3("baseColor", _this.color);
  68512. effect.setFloat("depth", _this.depth);
  68513. effect.setFloat("colorLevel", _this.colorLevel);
  68514. effect.setTexture("refractionSampler", _this._refTexture);
  68515. });
  68516. return _this;
  68517. }
  68518. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  68519. /**
  68520. * Gets or sets the refraction texture
  68521. * Please note that you are responsible for disposing the texture if you set it manually
  68522. */
  68523. get: function () {
  68524. return this._refTexture;
  68525. },
  68526. set: function (value) {
  68527. if (this._refTexture && this._ownRefractionTexture) {
  68528. this._refTexture.dispose();
  68529. }
  68530. this._refTexture = value;
  68531. this._ownRefractionTexture = false;
  68532. },
  68533. enumerable: true,
  68534. configurable: true
  68535. });
  68536. // Methods
  68537. RefractionPostProcess.prototype.dispose = function (camera) {
  68538. if (this._refTexture && this._ownRefractionTexture) {
  68539. this._refTexture.dispose();
  68540. this._refTexture = null;
  68541. }
  68542. _super.prototype.dispose.call(this, camera);
  68543. };
  68544. return RefractionPostProcess;
  68545. }(BABYLON.PostProcess));
  68546. BABYLON.RefractionPostProcess = RefractionPostProcess;
  68547. })(BABYLON || (BABYLON = {}));
  68548. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  68549. var BABYLON;
  68550. (function (BABYLON) {
  68551. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  68552. __extends(BlackAndWhitePostProcess, _super);
  68553. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  68554. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  68555. _this.degree = 1;
  68556. _this.onApplyObservable.add(function (effect) {
  68557. effect.setFloat("degree", _this.degree);
  68558. });
  68559. return _this;
  68560. }
  68561. return BlackAndWhitePostProcess;
  68562. }(BABYLON.PostProcess));
  68563. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  68564. })(BABYLON || (BABYLON = {}));
  68565. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  68566. var BABYLON;
  68567. (function (BABYLON) {
  68568. var ConvolutionPostProcess = /** @class */ (function (_super) {
  68569. __extends(ConvolutionPostProcess, _super);
  68570. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  68571. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  68572. _this.kernel = kernel;
  68573. _this.onApply = function (effect) {
  68574. effect.setFloat2("screenSize", _this.width, _this.height);
  68575. effect.setArray("kernel", _this.kernel);
  68576. };
  68577. return _this;
  68578. }
  68579. // Statics
  68580. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68581. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  68582. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  68583. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  68584. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  68585. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  68586. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  68587. return ConvolutionPostProcess;
  68588. }(BABYLON.PostProcess));
  68589. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  68590. })(BABYLON || (BABYLON = {}));
  68591. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  68592. var BABYLON;
  68593. (function (BABYLON) {
  68594. var FilterPostProcess = /** @class */ (function (_super) {
  68595. __extends(FilterPostProcess, _super);
  68596. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  68597. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  68598. _this.kernelMatrix = kernelMatrix;
  68599. _this.onApply = function (effect) {
  68600. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  68601. };
  68602. return _this;
  68603. }
  68604. return FilterPostProcess;
  68605. }(BABYLON.PostProcess));
  68606. BABYLON.FilterPostProcess = FilterPostProcess;
  68607. })(BABYLON || (BABYLON = {}));
  68608. //# sourceMappingURL=babylon.filterPostProcess.js.map
  68609. var BABYLON;
  68610. (function (BABYLON) {
  68611. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  68612. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  68613. __extends(VolumetricLightScatteringPostProcess, _super);
  68614. /**
  68615. * @constructor
  68616. * @param {string} name - The post-process name
  68617. * @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)
  68618. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  68619. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  68620. * @param {number} samples - The post-process quality, default 100
  68621. * @param {number} samplingMode - The post-process filtering mode
  68622. * @param {BABYLON.Engine} engine - The babylon engine
  68623. * @param {boolean} reusable - If the post-process is reusable
  68624. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  68625. */
  68626. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  68627. if (samples === void 0) { samples = 100; }
  68628. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68629. 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;
  68630. _this._screenCoordinates = BABYLON.Vector2.Zero();
  68631. /**
  68632. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  68633. * @type {Vector3}
  68634. */
  68635. _this.customMeshPosition = BABYLON.Vector3.Zero();
  68636. /**
  68637. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  68638. * @type {boolean}
  68639. */
  68640. _this.useCustomMeshPosition = false;
  68641. /**
  68642. * If the post-process should inverse the light scattering direction
  68643. * @type {boolean}
  68644. */
  68645. _this.invert = true;
  68646. /**
  68647. * Array containing the excluded meshes not rendered in the internal pass
  68648. */
  68649. _this.excludedMeshes = new Array();
  68650. /**
  68651. * Controls the overall intensity of the post-process
  68652. * @type {number}
  68653. */
  68654. _this.exposure = 0.3;
  68655. /**
  68656. * Dissipates each sample's contribution in range [0, 1]
  68657. * @type {number}
  68658. */
  68659. _this.decay = 0.96815;
  68660. /**
  68661. * Controls the overall intensity of each sample
  68662. * @type {number}
  68663. */
  68664. _this.weight = 0.58767;
  68665. /**
  68666. * Controls the density of each sample
  68667. * @type {number}
  68668. */
  68669. _this.density = 0.926;
  68670. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  68671. engine = scene.getEngine();
  68672. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  68673. // Configure mesh
  68674. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  68675. // Configure
  68676. _this._createPass(scene, ratio.passRatio || ratio);
  68677. _this.onActivate = function (camera) {
  68678. if (!_this.isSupported) {
  68679. _this.dispose(camera);
  68680. }
  68681. _this.onActivate = null;
  68682. };
  68683. _this.onApplyObservable.add(function (effect) {
  68684. _this._updateMeshScreenCoordinates(scene);
  68685. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  68686. effect.setFloat("exposure", _this.exposure);
  68687. effect.setFloat("decay", _this.decay);
  68688. effect.setFloat("weight", _this.weight);
  68689. effect.setFloat("density", _this.density);
  68690. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  68691. });
  68692. return _this;
  68693. }
  68694. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  68695. get: function () {
  68696. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68697. return false;
  68698. },
  68699. set: function (useDiffuseColor) {
  68700. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68701. },
  68702. enumerable: true,
  68703. configurable: true
  68704. });
  68705. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  68706. return "VolumetricLightScatteringPostProcess";
  68707. };
  68708. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  68709. var mesh = subMesh.getMesh();
  68710. // Render this.mesh as default
  68711. if (mesh === this.mesh && mesh.material) {
  68712. return mesh.material.isReady(mesh);
  68713. }
  68714. var defines = [];
  68715. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68716. var material = subMesh.getMaterial();
  68717. // Alpha test
  68718. if (material) {
  68719. if (material.needAlphaTesting()) {
  68720. defines.push("#define ALPHATEST");
  68721. }
  68722. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68723. attribs.push(BABYLON.VertexBuffer.UVKind);
  68724. defines.push("#define UV1");
  68725. }
  68726. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68727. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68728. defines.push("#define UV2");
  68729. }
  68730. }
  68731. // Bones
  68732. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68733. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68734. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68735. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68736. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  68737. }
  68738. else {
  68739. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68740. }
  68741. // Instances
  68742. if (useInstances) {
  68743. defines.push("#define INSTANCES");
  68744. attribs.push("world0");
  68745. attribs.push("world1");
  68746. attribs.push("world2");
  68747. attribs.push("world3");
  68748. }
  68749. // Get correct effect
  68750. var join = defines.join("\n");
  68751. if (this._cachedDefines !== join) {
  68752. this._cachedDefines = join;
  68753. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  68754. }
  68755. return this._volumetricLightScatteringPass.isReady();
  68756. };
  68757. /**
  68758. * Sets the new light position for light scattering effect
  68759. * @param {BABYLON.Vector3} The new custom light position
  68760. */
  68761. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  68762. this.customMeshPosition = position;
  68763. };
  68764. /**
  68765. * Returns the light position for light scattering effect
  68766. * @return {BABYLON.Vector3} The custom light position
  68767. */
  68768. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  68769. return this.customMeshPosition;
  68770. };
  68771. /**
  68772. * Disposes the internal assets and detaches the post-process from the camera
  68773. */
  68774. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  68775. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  68776. if (rttIndex !== -1) {
  68777. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  68778. }
  68779. this._volumetricLightScatteringRTT.dispose();
  68780. _super.prototype.dispose.call(this, camera);
  68781. };
  68782. /**
  68783. * Returns the render target texture used by the post-process
  68784. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  68785. */
  68786. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  68787. return this._volumetricLightScatteringRTT;
  68788. };
  68789. // Private methods
  68790. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  68791. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  68792. return true;
  68793. }
  68794. return false;
  68795. };
  68796. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  68797. var _this = this;
  68798. var engine = scene.getEngine();
  68799. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68800. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68801. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68802. this._volumetricLightScatteringRTT.renderList = null;
  68803. this._volumetricLightScatteringRTT.renderParticles = false;
  68804. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  68805. var camera = this.getCamera();
  68806. if (camera) {
  68807. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  68808. }
  68809. else {
  68810. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  68811. }
  68812. // Custom render function for submeshes
  68813. var renderSubMesh = function (subMesh) {
  68814. var mesh = subMesh.getRenderingMesh();
  68815. if (_this._meshExcluded(mesh)) {
  68816. return;
  68817. }
  68818. var material = subMesh.getMaterial();
  68819. if (!material) {
  68820. return;
  68821. }
  68822. var scene = mesh.getScene();
  68823. var engine = scene.getEngine();
  68824. // Culling
  68825. engine.setState(material.backFaceCulling);
  68826. // Managing instances
  68827. var batch = mesh._getInstancesRenderList(subMesh._id);
  68828. if (batch.mustReturn) {
  68829. return;
  68830. }
  68831. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68832. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  68833. var effect = _this._volumetricLightScatteringPass;
  68834. if (mesh === _this.mesh) {
  68835. if (subMesh.effect) {
  68836. effect = subMesh.effect;
  68837. }
  68838. else {
  68839. effect = material.getEffect();
  68840. }
  68841. }
  68842. engine.enableEffect(effect);
  68843. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  68844. if (mesh === _this.mesh) {
  68845. material.bind(mesh.getWorldMatrix(), mesh);
  68846. }
  68847. else {
  68848. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  68849. // Alpha test
  68850. if (material && material.needAlphaTesting()) {
  68851. var alphaTexture = material.getAlphaTestTexture();
  68852. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  68853. if (alphaTexture) {
  68854. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68855. }
  68856. }
  68857. // Bones
  68858. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68859. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68860. }
  68861. }
  68862. // Draw
  68863. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  68864. }
  68865. };
  68866. // Render target texture callbacks
  68867. var savedSceneClearColor;
  68868. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  68869. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  68870. savedSceneClearColor = scene.clearColor;
  68871. scene.clearColor = sceneClearColor;
  68872. });
  68873. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  68874. scene.clearColor = savedSceneClearColor;
  68875. });
  68876. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68877. var engine = scene.getEngine();
  68878. var index;
  68879. if (depthOnlySubMeshes.length) {
  68880. engine.setColorWrite(false);
  68881. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68882. renderSubMesh(depthOnlySubMeshes.data[index]);
  68883. }
  68884. engine.setColorWrite(true);
  68885. }
  68886. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68887. renderSubMesh(opaqueSubMeshes.data[index]);
  68888. }
  68889. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68890. renderSubMesh(alphaTestSubMeshes.data[index]);
  68891. }
  68892. if (transparentSubMeshes.length) {
  68893. // Sort sub meshes
  68894. for (index = 0; index < transparentSubMeshes.length; index++) {
  68895. var submesh = transparentSubMeshes.data[index];
  68896. var boundingInfo = submesh.getBoundingInfo();
  68897. if (boundingInfo && scene.activeCamera) {
  68898. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  68899. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  68900. }
  68901. }
  68902. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  68903. sortedArray.sort(function (a, b) {
  68904. // Alpha index first
  68905. if (a._alphaIndex > b._alphaIndex) {
  68906. return 1;
  68907. }
  68908. if (a._alphaIndex < b._alphaIndex) {
  68909. return -1;
  68910. }
  68911. // Then distance to camera
  68912. if (a._distanceToCamera < b._distanceToCamera) {
  68913. return 1;
  68914. }
  68915. if (a._distanceToCamera > b._distanceToCamera) {
  68916. return -1;
  68917. }
  68918. return 0;
  68919. });
  68920. // Render sub meshes
  68921. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  68922. for (index = 0; index < sortedArray.length; index++) {
  68923. renderSubMesh(sortedArray[index]);
  68924. }
  68925. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68926. }
  68927. };
  68928. };
  68929. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  68930. var transform = scene.getTransformMatrix();
  68931. var meshPosition;
  68932. if (this.useCustomMeshPosition) {
  68933. meshPosition = this.customMeshPosition;
  68934. }
  68935. else if (this.attachedNode) {
  68936. meshPosition = this.attachedNode.position;
  68937. }
  68938. else {
  68939. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  68940. }
  68941. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  68942. this._screenCoordinates.x = pos.x / this._viewPort.width;
  68943. this._screenCoordinates.y = pos.y / this._viewPort.height;
  68944. if (this.invert)
  68945. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  68946. };
  68947. // Static methods
  68948. /**
  68949. * Creates a default mesh for the Volumeric Light Scattering post-process
  68950. * @param {string} The mesh name
  68951. * @param {BABYLON.Scene} The scene where to create the mesh
  68952. * @return {BABYLON.Mesh} the default mesh
  68953. */
  68954. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  68955. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  68956. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  68957. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  68958. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  68959. mesh.material = material;
  68960. return mesh;
  68961. };
  68962. __decorate([
  68963. BABYLON.serializeAsVector3()
  68964. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  68965. __decorate([
  68966. BABYLON.serialize()
  68967. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  68968. __decorate([
  68969. BABYLON.serialize()
  68970. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  68971. __decorate([
  68972. BABYLON.serializeAsMeshReference()
  68973. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  68974. __decorate([
  68975. BABYLON.serialize()
  68976. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  68977. __decorate([
  68978. BABYLON.serialize()
  68979. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  68980. __decorate([
  68981. BABYLON.serialize()
  68982. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  68983. __decorate([
  68984. BABYLON.serialize()
  68985. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  68986. __decorate([
  68987. BABYLON.serialize()
  68988. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  68989. return VolumetricLightScatteringPostProcess;
  68990. }(BABYLON.PostProcess));
  68991. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  68992. })(BABYLON || (BABYLON = {}));
  68993. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  68994. //
  68995. // This post-process allows the modification of rendered colors by using
  68996. // a 'look-up table' (LUT). This effect is also called Color Grading.
  68997. //
  68998. // The object needs to be provided an url to a texture containing the color
  68999. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  69000. // Use an image editing software to tweak the LUT to match your needs.
  69001. //
  69002. // For an example of a color LUT, see here:
  69003. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  69004. // For explanations on color grading, see here:
  69005. // http://udn.epicgames.com/Three/ColorGrading.html
  69006. //
  69007. var BABYLON;
  69008. (function (BABYLON) {
  69009. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  69010. __extends(ColorCorrectionPostProcess, _super);
  69011. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  69012. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  69013. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69014. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  69015. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69016. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69017. _this.onApply = function (effect) {
  69018. effect.setTexture("colorTable", _this._colorTableTexture);
  69019. };
  69020. return _this;
  69021. }
  69022. return ColorCorrectionPostProcess;
  69023. }(BABYLON.PostProcess));
  69024. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  69025. })(BABYLON || (BABYLON = {}));
  69026. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  69027. var BABYLON;
  69028. (function (BABYLON) {
  69029. var TonemappingOperator;
  69030. (function (TonemappingOperator) {
  69031. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  69032. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  69033. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  69034. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  69035. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  69036. ;
  69037. var TonemapPostProcess = /** @class */ (function (_super) {
  69038. __extends(TonemapPostProcess, _super);
  69039. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  69040. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69041. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69042. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  69043. _this._operator = _operator;
  69044. _this.exposureAdjustment = exposureAdjustment;
  69045. var defines = "#define ";
  69046. if (_this._operator === TonemappingOperator.Hable)
  69047. defines += "HABLE_TONEMAPPING";
  69048. else if (_this._operator === TonemappingOperator.Reinhard)
  69049. defines += "REINHARD_TONEMAPPING";
  69050. else if (_this._operator === TonemappingOperator.HejiDawson)
  69051. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  69052. else if (_this._operator === TonemappingOperator.Photographic)
  69053. defines += "PHOTOGRAPHIC_TONEMAPPING";
  69054. //sadly a second call to create the effect.
  69055. _this.updateEffect(defines);
  69056. _this.onApply = function (effect) {
  69057. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  69058. };
  69059. return _this;
  69060. }
  69061. return TonemapPostProcess;
  69062. }(BABYLON.PostProcess));
  69063. BABYLON.TonemapPostProcess = TonemapPostProcess;
  69064. })(BABYLON || (BABYLON = {}));
  69065. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  69066. var BABYLON;
  69067. (function (BABYLON) {
  69068. var DisplayPassPostProcess = /** @class */ (function (_super) {
  69069. __extends(DisplayPassPostProcess, _super);
  69070. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  69071. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  69072. }
  69073. return DisplayPassPostProcess;
  69074. }(BABYLON.PostProcess));
  69075. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  69076. })(BABYLON || (BABYLON = {}));
  69077. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  69078. var BABYLON;
  69079. (function (BABYLON) {
  69080. var HighlightsPostProcess = /** @class */ (function (_super) {
  69081. __extends(HighlightsPostProcess, _super);
  69082. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69083. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69084. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69085. }
  69086. return HighlightsPostProcess;
  69087. }(BABYLON.PostProcess));
  69088. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  69089. })(BABYLON || (BABYLON = {}));
  69090. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  69091. var BABYLON;
  69092. (function (BABYLON) {
  69093. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  69094. __extends(ImageProcessingPostProcess, _super);
  69095. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  69096. if (camera === void 0) { camera = null; }
  69097. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69098. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  69099. _this._fromLinearSpace = true;
  69100. /**
  69101. * Defines cache preventing GC.
  69102. */
  69103. _this._defines = {
  69104. IMAGEPROCESSING: false,
  69105. VIGNETTE: false,
  69106. VIGNETTEBLENDMODEMULTIPLY: false,
  69107. VIGNETTEBLENDMODEOPAQUE: false,
  69108. TONEMAPPING: false,
  69109. CONTRAST: false,
  69110. COLORCURVES: false,
  69111. COLORGRADING: false,
  69112. COLORGRADING3D: false,
  69113. FROMLINEARSPACE: false,
  69114. SAMPLER3DGREENDEPTH: false,
  69115. SAMPLER3DBGRMAP: false,
  69116. IMAGEPROCESSINGPOSTPROCESS: false,
  69117. EXPOSURE: false,
  69118. };
  69119. // Setup the configuration as forced by the constructor. This would then not force the
  69120. // scene materials output in linear space and let untouched the default forward pass.
  69121. if (imageProcessingConfiguration) {
  69122. imageProcessingConfiguration.applyByPostProcess = true;
  69123. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  69124. // This will cause the shader to be compiled
  69125. _this.fromLinearSpace = false;
  69126. }
  69127. else {
  69128. _this._attachImageProcessingConfiguration(null, true);
  69129. _this.imageProcessingConfiguration.applyByPostProcess = true;
  69130. }
  69131. _this.onApply = function (effect) {
  69132. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  69133. };
  69134. return _this;
  69135. }
  69136. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  69137. /**
  69138. * Gets the image processing configuration used either in this material.
  69139. */
  69140. get: function () {
  69141. return this._imageProcessingConfiguration;
  69142. },
  69143. /**
  69144. * Sets the Default image processing configuration used either in the this material.
  69145. *
  69146. * If sets to null, the scene one is in use.
  69147. */
  69148. set: function (value) {
  69149. this._attachImageProcessingConfiguration(value);
  69150. },
  69151. enumerable: true,
  69152. configurable: true
  69153. });
  69154. /**
  69155. * Attaches a new image processing configuration to the PBR Material.
  69156. * @param configuration
  69157. */
  69158. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  69159. var _this = this;
  69160. if (doNotBuild === void 0) { doNotBuild = false; }
  69161. if (configuration === this._imageProcessingConfiguration) {
  69162. return;
  69163. }
  69164. // Detaches observer.
  69165. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69166. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69167. }
  69168. // Pick the scene configuration if needed.
  69169. if (!configuration) {
  69170. var scene = null;
  69171. var engine = this.getEngine();
  69172. var camera = this.getCamera();
  69173. if (camera) {
  69174. scene = camera.getScene();
  69175. }
  69176. else if (engine && engine.scenes) {
  69177. var scenes = engine.scenes;
  69178. scene = scenes[scenes.length - 1];
  69179. }
  69180. else {
  69181. scene = BABYLON.Engine.LastCreatedScene;
  69182. }
  69183. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  69184. }
  69185. else {
  69186. this._imageProcessingConfiguration = configuration;
  69187. }
  69188. // Attaches observer.
  69189. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  69190. _this._updateParameters();
  69191. });
  69192. // Ensure the effect will be rebuilt.
  69193. if (!doNotBuild) {
  69194. this._updateParameters();
  69195. }
  69196. };
  69197. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  69198. /**
  69199. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69200. */
  69201. get: function () {
  69202. return this.imageProcessingConfiguration.colorCurves;
  69203. },
  69204. /**
  69205. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69206. */
  69207. set: function (value) {
  69208. this.imageProcessingConfiguration.colorCurves = value;
  69209. },
  69210. enumerable: true,
  69211. configurable: true
  69212. });
  69213. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  69214. /**
  69215. * Gets wether the color curves effect is enabled.
  69216. */
  69217. get: function () {
  69218. return this.imageProcessingConfiguration.colorCurvesEnabled;
  69219. },
  69220. /**
  69221. * Sets wether the color curves effect is enabled.
  69222. */
  69223. set: function (value) {
  69224. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  69225. },
  69226. enumerable: true,
  69227. configurable: true
  69228. });
  69229. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  69230. /**
  69231. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69232. */
  69233. get: function () {
  69234. return this.imageProcessingConfiguration.colorGradingTexture;
  69235. },
  69236. /**
  69237. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69238. */
  69239. set: function (value) {
  69240. this.imageProcessingConfiguration.colorGradingTexture = value;
  69241. },
  69242. enumerable: true,
  69243. configurable: true
  69244. });
  69245. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  69246. /**
  69247. * Gets wether the color grading effect is enabled.
  69248. */
  69249. get: function () {
  69250. return this.imageProcessingConfiguration.colorGradingEnabled;
  69251. },
  69252. /**
  69253. * Gets wether the color grading effect is enabled.
  69254. */
  69255. set: function (value) {
  69256. this.imageProcessingConfiguration.colorGradingEnabled = value;
  69257. },
  69258. enumerable: true,
  69259. configurable: true
  69260. });
  69261. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  69262. /**
  69263. * Gets exposure used in the effect.
  69264. */
  69265. get: function () {
  69266. return this.imageProcessingConfiguration.exposure;
  69267. },
  69268. /**
  69269. * Sets exposure used in the effect.
  69270. */
  69271. set: function (value) {
  69272. this.imageProcessingConfiguration.exposure = value;
  69273. },
  69274. enumerable: true,
  69275. configurable: true
  69276. });
  69277. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  69278. /**
  69279. * Gets wether tonemapping is enabled or not.
  69280. */
  69281. get: function () {
  69282. return this._imageProcessingConfiguration.toneMappingEnabled;
  69283. },
  69284. /**
  69285. * Sets wether tonemapping is enabled or not
  69286. */
  69287. set: function (value) {
  69288. this._imageProcessingConfiguration.toneMappingEnabled = value;
  69289. },
  69290. enumerable: true,
  69291. configurable: true
  69292. });
  69293. ;
  69294. ;
  69295. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  69296. /**
  69297. * Gets contrast used in the effect.
  69298. */
  69299. get: function () {
  69300. return this.imageProcessingConfiguration.contrast;
  69301. },
  69302. /**
  69303. * Sets contrast used in the effect.
  69304. */
  69305. set: function (value) {
  69306. this.imageProcessingConfiguration.contrast = value;
  69307. },
  69308. enumerable: true,
  69309. configurable: true
  69310. });
  69311. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  69312. /**
  69313. * Gets Vignette stretch size.
  69314. */
  69315. get: function () {
  69316. return this.imageProcessingConfiguration.vignetteStretch;
  69317. },
  69318. /**
  69319. * Sets Vignette stretch size.
  69320. */
  69321. set: function (value) {
  69322. this.imageProcessingConfiguration.vignetteStretch = value;
  69323. },
  69324. enumerable: true,
  69325. configurable: true
  69326. });
  69327. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  69328. /**
  69329. * Gets Vignette centre X Offset.
  69330. */
  69331. get: function () {
  69332. return this.imageProcessingConfiguration.vignetteCentreX;
  69333. },
  69334. /**
  69335. * Sets Vignette centre X Offset.
  69336. */
  69337. set: function (value) {
  69338. this.imageProcessingConfiguration.vignetteCentreX = value;
  69339. },
  69340. enumerable: true,
  69341. configurable: true
  69342. });
  69343. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  69344. /**
  69345. * Gets Vignette centre Y Offset.
  69346. */
  69347. get: function () {
  69348. return this.imageProcessingConfiguration.vignetteCentreY;
  69349. },
  69350. /**
  69351. * Sets Vignette centre Y Offset.
  69352. */
  69353. set: function (value) {
  69354. this.imageProcessingConfiguration.vignetteCentreY = value;
  69355. },
  69356. enumerable: true,
  69357. configurable: true
  69358. });
  69359. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  69360. /**
  69361. * Gets Vignette weight or intensity of the vignette effect.
  69362. */
  69363. get: function () {
  69364. return this.imageProcessingConfiguration.vignetteWeight;
  69365. },
  69366. /**
  69367. * Sets Vignette weight or intensity of the vignette effect.
  69368. */
  69369. set: function (value) {
  69370. this.imageProcessingConfiguration.vignetteWeight = value;
  69371. },
  69372. enumerable: true,
  69373. configurable: true
  69374. });
  69375. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  69376. /**
  69377. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69378. * if vignetteEnabled is set to true.
  69379. */
  69380. get: function () {
  69381. return this.imageProcessingConfiguration.vignetteColor;
  69382. },
  69383. /**
  69384. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69385. * if vignetteEnabled is set to true.
  69386. */
  69387. set: function (value) {
  69388. this.imageProcessingConfiguration.vignetteColor = value;
  69389. },
  69390. enumerable: true,
  69391. configurable: true
  69392. });
  69393. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  69394. /**
  69395. * Gets Camera field of view used by the Vignette effect.
  69396. */
  69397. get: function () {
  69398. return this.imageProcessingConfiguration.vignetteCameraFov;
  69399. },
  69400. /**
  69401. * Sets Camera field of view used by the Vignette effect.
  69402. */
  69403. set: function (value) {
  69404. this.imageProcessingConfiguration.vignetteCameraFov = value;
  69405. },
  69406. enumerable: true,
  69407. configurable: true
  69408. });
  69409. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  69410. /**
  69411. * Gets the vignette blend mode allowing different kind of effect.
  69412. */
  69413. get: function () {
  69414. return this.imageProcessingConfiguration.vignetteBlendMode;
  69415. },
  69416. /**
  69417. * Sets the vignette blend mode allowing different kind of effect.
  69418. */
  69419. set: function (value) {
  69420. this.imageProcessingConfiguration.vignetteBlendMode = value;
  69421. },
  69422. enumerable: true,
  69423. configurable: true
  69424. });
  69425. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  69426. /**
  69427. * Gets wether the vignette effect is enabled.
  69428. */
  69429. get: function () {
  69430. return this.imageProcessingConfiguration.vignetteEnabled;
  69431. },
  69432. /**
  69433. * Sets wether the vignette effect is enabled.
  69434. */
  69435. set: function (value) {
  69436. this.imageProcessingConfiguration.vignetteEnabled = value;
  69437. },
  69438. enumerable: true,
  69439. configurable: true
  69440. });
  69441. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  69442. /**
  69443. * Gets wether the input of the processing is in Gamma or Linear Space.
  69444. */
  69445. get: function () {
  69446. return this._fromLinearSpace;
  69447. },
  69448. /**
  69449. * Sets wether the input of the processing is in Gamma or Linear Space.
  69450. */
  69451. set: function (value) {
  69452. if (this._fromLinearSpace === value) {
  69453. return;
  69454. }
  69455. this._fromLinearSpace = value;
  69456. this._updateParameters();
  69457. },
  69458. enumerable: true,
  69459. configurable: true
  69460. });
  69461. ImageProcessingPostProcess.prototype.getClassName = function () {
  69462. return "ImageProcessingPostProcess";
  69463. };
  69464. ImageProcessingPostProcess.prototype._updateParameters = function () {
  69465. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  69466. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  69467. var defines = "";
  69468. for (var define in this._defines) {
  69469. if (this._defines[define]) {
  69470. defines += "#define " + define + ";\r\n";
  69471. }
  69472. }
  69473. var samplers = ["textureSampler"];
  69474. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  69475. var uniforms = ["scale"];
  69476. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  69477. this.updateEffect(defines, uniforms, samplers);
  69478. };
  69479. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  69480. _super.prototype.dispose.call(this, camera);
  69481. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69482. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69483. }
  69484. this.imageProcessingConfiguration.applyByPostProcess = false;
  69485. };
  69486. __decorate([
  69487. BABYLON.serialize()
  69488. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  69489. return ImageProcessingPostProcess;
  69490. }(BABYLON.PostProcess));
  69491. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  69492. })(BABYLON || (BABYLON = {}));
  69493. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  69494. var BABYLON;
  69495. (function (BABYLON) {
  69496. /**
  69497. * The Blur Post Process which blurs an image based on a kernel and direction.
  69498. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69499. */
  69500. var BlurPostProcess = /** @class */ (function (_super) {
  69501. __extends(BlurPostProcess, _super);
  69502. /**
  69503. * Creates a new instance of @see BlurPostProcess
  69504. * @param name The name of the effect.
  69505. * @param direction The direction in which to blur the image.
  69506. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
  69507. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69508. * @param camera The camera to apply the render pass to.
  69509. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69510. * @param engine The engine which the post process will be applied. (default: current engine)
  69511. * @param reusable If the post process can be reused on the same frame. (default: false)
  69512. * @param textureType Type of textures used when performing the post process. (default: 0)
  69513. */
  69514. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  69515. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69516. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69517. if (defines === void 0) { defines = ""; }
  69518. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  69519. _this.direction = direction;
  69520. _this._packedFloat = false;
  69521. _this._staticDefines = "";
  69522. _this._staticDefines = defines;
  69523. _this.onApplyObservable.add(function (effect) {
  69524. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69525. });
  69526. _this.kernel = kernel;
  69527. return _this;
  69528. }
  69529. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69530. /**
  69531. * Gets the length in pixels of the blur sample region
  69532. */
  69533. get: function () {
  69534. return this._idealKernel;
  69535. },
  69536. /**
  69537. * Sets the length in pixels of the blur sample region
  69538. */
  69539. set: function (v) {
  69540. if (this._idealKernel === v) {
  69541. return;
  69542. }
  69543. v = Math.max(v, 1);
  69544. this._idealKernel = v;
  69545. this._kernel = this._nearestBestKernel(v);
  69546. this._updateParameters();
  69547. },
  69548. enumerable: true,
  69549. configurable: true
  69550. });
  69551. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69552. /**
  69553. * Gets wether or not the blur is unpacking/repacking floats
  69554. */
  69555. get: function () {
  69556. return this._packedFloat;
  69557. },
  69558. /**
  69559. * Sets wether or not the blur needs to unpack/repack floats
  69560. */
  69561. set: function (v) {
  69562. if (this._packedFloat === v) {
  69563. return;
  69564. }
  69565. this._packedFloat = v;
  69566. this._updateParameters();
  69567. },
  69568. enumerable: true,
  69569. configurable: true
  69570. });
  69571. BlurPostProcess.prototype._updateParameters = function () {
  69572. // Generate sampling offsets and weights
  69573. var N = this._kernel;
  69574. var centerIndex = (N - 1) / 2;
  69575. // Generate Gaussian sampling weights over kernel
  69576. var offsets = [];
  69577. var weights = [];
  69578. var totalWeight = 0;
  69579. for (var i = 0; i < N; i++) {
  69580. var u = i / (N - 1);
  69581. var w = this._gaussianWeight(u * 2.0 - 1);
  69582. offsets[i] = (i - centerIndex);
  69583. weights[i] = w;
  69584. totalWeight += w;
  69585. }
  69586. // Normalize weights
  69587. for (var i = 0; i < weights.length; i++) {
  69588. weights[i] /= totalWeight;
  69589. }
  69590. // Optimize: combine samples to take advantage of hardware linear sampling
  69591. // Walk from left to center, combining pairs (symmetrically)
  69592. var linearSamplingWeights = [];
  69593. var linearSamplingOffsets = [];
  69594. var linearSamplingMap = [];
  69595. for (var i = 0; i <= centerIndex; i += 2) {
  69596. var j = Math.min(i + 1, Math.floor(centerIndex));
  69597. var singleCenterSample = i === j;
  69598. if (singleCenterSample) {
  69599. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69600. }
  69601. else {
  69602. var sharedCell = j === centerIndex;
  69603. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69604. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69605. if (offsetLinear === 0) {
  69606. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69607. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69608. }
  69609. else {
  69610. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69611. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69612. }
  69613. }
  69614. }
  69615. for (var i = 0; i < linearSamplingMap.length; i++) {
  69616. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69617. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69618. }
  69619. // Replace with optimized
  69620. offsets = linearSamplingOffsets;
  69621. weights = linearSamplingWeights;
  69622. // Generate shaders
  69623. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69624. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69625. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69626. var defines = "";
  69627. defines += this._staticDefines;
  69628. for (var i = 0; i < varyingCount; i++) {
  69629. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69630. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69631. }
  69632. var depCount = 0;
  69633. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69634. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69635. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69636. depCount++;
  69637. }
  69638. if (this.packedFloat) {
  69639. defines += "#define PACKEDFLOAT 1";
  69640. }
  69641. this.updateEffect(defines, null, null, {
  69642. varyingCount: varyingCount,
  69643. depCount: depCount
  69644. });
  69645. };
  69646. /**
  69647. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69648. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69649. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69650. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69651. * The gaps between physical kernels are compensated for in the weighting of the samples
  69652. * @param idealKernel Ideal blur kernel.
  69653. * @return Nearest best kernel.
  69654. */
  69655. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69656. var v = Math.round(idealKernel);
  69657. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69658. var k = _a[_i];
  69659. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69660. return Math.max(k, 3);
  69661. }
  69662. }
  69663. return Math.max(v, 3);
  69664. };
  69665. /**
  69666. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69667. * @param x The point on the Gaussian distribution to sample.
  69668. * @return the value of the Gaussian function at x.
  69669. */
  69670. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69671. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69672. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69673. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69674. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69675. // truncated at around 1.3% of peak strength.
  69676. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69677. var sigma = (1 / 3);
  69678. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69679. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69680. var weight = (1.0 / denominator) * Math.exp(exponent);
  69681. return weight;
  69682. };
  69683. /**
  69684. * Generates a string that can be used as a floating point number in GLSL.
  69685. * @param x Value to print.
  69686. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69687. * @return GLSL float string.
  69688. */
  69689. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69690. if (decimalFigures === void 0) { decimalFigures = 8; }
  69691. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69692. };
  69693. return BlurPostProcess;
  69694. }(BABYLON.PostProcess));
  69695. BABYLON.BlurPostProcess = BlurPostProcess;
  69696. })(BABYLON || (BABYLON = {}));
  69697. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69698. var BABYLON;
  69699. (function (BABYLON) {
  69700. /**
  69701. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  69702. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  69703. * based on samples that have a large difference in distance than the center pixel.
  69704. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69705. */
  69706. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  69707. __extends(DepthOfFieldBlurPostProcess, _super);
  69708. /**
  69709. * Creates a new instance of @see CircleOfConfusionPostProcess
  69710. * @param name The name of the effect.
  69711. * @param scene The scene the effect belongs to.
  69712. * @param direction The direction the blur should be applied.
  69713. * @param kernel The size of the kernel used to blur.
  69714. * @param options The required width/height ratio to downsize to before computing the render pass.
  69715. * @param camera The camera to apply the render pass to.
  69716. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  69717. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  69718. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69719. * @param engine The engine which the post process will be applied. (default: current engine)
  69720. * @param reusable If the post process can be reused on the same frame. (default: false)
  69721. * @param textureType Type of textures used when performing the post process. (default: 0)
  69722. */
  69723. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType) {
  69724. if (imageToBlur === void 0) { imageToBlur = null; }
  69725. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69726. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69727. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n") || this;
  69728. _this.direction = direction;
  69729. _this.onApplyObservable.add(function (effect) {
  69730. if (imageToBlur != null) {
  69731. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  69732. }
  69733. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  69734. if (scene.activeCamera) {
  69735. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69736. }
  69737. });
  69738. return _this;
  69739. }
  69740. return DepthOfFieldBlurPostProcess;
  69741. }(BABYLON.BlurPostProcess));
  69742. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  69743. })(BABYLON || (BABYLON = {}));
  69744. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  69745. var BABYLON;
  69746. (function (BABYLON) {
  69747. var Bone = /** @class */ (function (_super) {
  69748. __extends(Bone, _super);
  69749. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  69750. if (parentBone === void 0) { parentBone = null; }
  69751. if (localMatrix === void 0) { localMatrix = null; }
  69752. if (restPose === void 0) { restPose = null; }
  69753. if (baseMatrix === void 0) { baseMatrix = null; }
  69754. if (index === void 0) { index = null; }
  69755. var _this = _super.call(this, name, skeleton.getScene()) || this;
  69756. _this.name = name;
  69757. _this.children = new Array();
  69758. _this.animations = new Array();
  69759. // Set this value to map this bone to a different index in the transform matrices.
  69760. // Set this value to -1 to exclude the bone from the transform matrices.
  69761. _this._index = null;
  69762. _this._worldTransform = new BABYLON.Matrix();
  69763. _this._absoluteTransform = new BABYLON.Matrix();
  69764. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  69765. _this._scaleMatrix = BABYLON.Matrix.Identity();
  69766. _this._scaleVector = BABYLON.Vector3.One();
  69767. _this._negateScaleChildren = BABYLON.Vector3.One();
  69768. _this._scalingDeterminant = 1;
  69769. _this._skeleton = skeleton;
  69770. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  69771. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  69772. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  69773. _this._index = index;
  69774. skeleton.bones.push(_this);
  69775. _this.setParent(parentBone, false);
  69776. _this._updateDifferenceMatrix();
  69777. return _this;
  69778. }
  69779. Object.defineProperty(Bone.prototype, "_matrix", {
  69780. get: function () {
  69781. return this._localMatrix;
  69782. },
  69783. set: function (val) {
  69784. if (this._localMatrix) {
  69785. this._localMatrix.copyFrom(val);
  69786. }
  69787. else {
  69788. this._localMatrix = val;
  69789. }
  69790. },
  69791. enumerable: true,
  69792. configurable: true
  69793. });
  69794. // Members
  69795. Bone.prototype.getSkeleton = function () {
  69796. return this._skeleton;
  69797. };
  69798. Bone.prototype.getParent = function () {
  69799. return this._parent;
  69800. };
  69801. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  69802. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  69803. if (this._parent === parent) {
  69804. return;
  69805. }
  69806. if (this._parent) {
  69807. var index = this._parent.children.indexOf(this);
  69808. if (index !== -1) {
  69809. this._parent.children.splice(index, 1);
  69810. }
  69811. }
  69812. this._parent = parent;
  69813. if (this._parent) {
  69814. this._parent.children.push(this);
  69815. }
  69816. if (updateDifferenceMatrix) {
  69817. this._updateDifferenceMatrix();
  69818. }
  69819. };
  69820. Bone.prototype.getLocalMatrix = function () {
  69821. return this._localMatrix;
  69822. };
  69823. Bone.prototype.getBaseMatrix = function () {
  69824. return this._baseMatrix;
  69825. };
  69826. Bone.prototype.getRestPose = function () {
  69827. return this._restPose;
  69828. };
  69829. Bone.prototype.returnToRest = function () {
  69830. this.updateMatrix(this._restPose.clone());
  69831. };
  69832. Bone.prototype.getWorldMatrix = function () {
  69833. return this._worldTransform;
  69834. };
  69835. Bone.prototype.getInvertedAbsoluteTransform = function () {
  69836. return this._invertedAbsoluteTransform;
  69837. };
  69838. Bone.prototype.getAbsoluteTransform = function () {
  69839. return this._absoluteTransform;
  69840. };
  69841. Object.defineProperty(Bone.prototype, "position", {
  69842. // Properties (matches AbstractMesh properties)
  69843. get: function () {
  69844. return this.getPosition();
  69845. },
  69846. set: function (newPosition) {
  69847. this.setPosition(newPosition);
  69848. },
  69849. enumerable: true,
  69850. configurable: true
  69851. });
  69852. Object.defineProperty(Bone.prototype, "rotation", {
  69853. get: function () {
  69854. return this.getRotation();
  69855. },
  69856. set: function (newRotation) {
  69857. this.setRotation(newRotation);
  69858. },
  69859. enumerable: true,
  69860. configurable: true
  69861. });
  69862. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  69863. get: function () {
  69864. return this.getRotationQuaternion();
  69865. },
  69866. set: function (newRotation) {
  69867. this.setRotationQuaternion(newRotation);
  69868. },
  69869. enumerable: true,
  69870. configurable: true
  69871. });
  69872. Object.defineProperty(Bone.prototype, "scaling", {
  69873. get: function () {
  69874. return this.getScale();
  69875. },
  69876. set: function (newScaling) {
  69877. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  69878. },
  69879. enumerable: true,
  69880. configurable: true
  69881. });
  69882. // Methods
  69883. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  69884. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  69885. this._baseMatrix = matrix.clone();
  69886. this._localMatrix = matrix.clone();
  69887. this._skeleton._markAsDirty();
  69888. if (updateDifferenceMatrix) {
  69889. this._updateDifferenceMatrix();
  69890. }
  69891. };
  69892. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  69893. if (!rootMatrix) {
  69894. rootMatrix = this._baseMatrix;
  69895. }
  69896. if (this._parent) {
  69897. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  69898. }
  69899. else {
  69900. this._absoluteTransform.copyFrom(rootMatrix);
  69901. }
  69902. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  69903. for (var index = 0; index < this.children.length; index++) {
  69904. this.children[index]._updateDifferenceMatrix();
  69905. }
  69906. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  69907. };
  69908. Bone.prototype.markAsDirty = function () {
  69909. this._currentRenderId++;
  69910. this._skeleton._markAsDirty();
  69911. };
  69912. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  69913. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  69914. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  69915. // all animation may be coming from a library skeleton, so may need to create animation
  69916. if (this.animations.length === 0) {
  69917. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  69918. this.animations[0].setKeys([]);
  69919. }
  69920. // get animation info / verify there is such a range from the source bone
  69921. var sourceRange = source.animations[0].getRange(rangeName);
  69922. if (!sourceRange) {
  69923. return false;
  69924. }
  69925. var from = sourceRange.from;
  69926. var to = sourceRange.to;
  69927. var sourceKeys = source.animations[0].getKeys();
  69928. // rescaling prep
  69929. var sourceBoneLength = source.length;
  69930. var sourceParent = source.getParent();
  69931. var parent = this.getParent();
  69932. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  69933. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  69934. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  69935. var destKeys = this.animations[0].getKeys();
  69936. // loop vars declaration
  69937. var orig;
  69938. var origTranslation;
  69939. var mat;
  69940. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  69941. orig = sourceKeys[key];
  69942. if (orig.frame >= from && orig.frame <= to) {
  69943. if (rescaleAsRequired) {
  69944. mat = orig.value.clone();
  69945. // scale based on parent ratio, when bone has parent
  69946. if (parentScalingReqd) {
  69947. origTranslation = mat.getTranslation();
  69948. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  69949. // scale based on skeleton dimension ratio when root bone, and value is passed
  69950. }
  69951. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  69952. origTranslation = mat.getTranslation();
  69953. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  69954. // use original when root bone, and no data for skelDimensionsRatio
  69955. }
  69956. else {
  69957. mat = orig.value;
  69958. }
  69959. }
  69960. else {
  69961. mat = orig.value;
  69962. }
  69963. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  69964. }
  69965. }
  69966. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  69967. return true;
  69968. };
  69969. /**
  69970. * Translate the bone in local or world space.
  69971. * @param vec The amount to translate the bone.
  69972. * @param space The space that the translation is in.
  69973. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69974. */
  69975. Bone.prototype.translate = function (vec, space, mesh) {
  69976. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69977. var lm = this.getLocalMatrix();
  69978. if (space == BABYLON.Space.LOCAL) {
  69979. lm.m[12] += vec.x;
  69980. lm.m[13] += vec.y;
  69981. lm.m[14] += vec.z;
  69982. }
  69983. else {
  69984. var wm = null;
  69985. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69986. if (mesh) {
  69987. wm = mesh.getWorldMatrix();
  69988. }
  69989. this._skeleton.computeAbsoluteTransforms();
  69990. var tmat = Bone._tmpMats[0];
  69991. var tvec = Bone._tmpVecs[0];
  69992. if (this._parent) {
  69993. if (mesh && wm) {
  69994. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69995. tmat.multiplyToRef(wm, tmat);
  69996. }
  69997. else {
  69998. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69999. }
  70000. }
  70001. tmat.m[12] = 0;
  70002. tmat.m[13] = 0;
  70003. tmat.m[14] = 0;
  70004. tmat.invert();
  70005. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  70006. lm.m[12] += tvec.x;
  70007. lm.m[13] += tvec.y;
  70008. lm.m[14] += tvec.z;
  70009. }
  70010. this.markAsDirty();
  70011. };
  70012. /**
  70013. * Set the postion of the bone in local or world space.
  70014. * @param position The position to set the bone.
  70015. * @param space The space that the position is in.
  70016. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70017. */
  70018. Bone.prototype.setPosition = function (position, space, mesh) {
  70019. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70020. var lm = this.getLocalMatrix();
  70021. if (space == BABYLON.Space.LOCAL) {
  70022. lm.m[12] = position.x;
  70023. lm.m[13] = position.y;
  70024. lm.m[14] = position.z;
  70025. }
  70026. else {
  70027. var wm = null;
  70028. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70029. if (mesh) {
  70030. wm = mesh.getWorldMatrix();
  70031. }
  70032. this._skeleton.computeAbsoluteTransforms();
  70033. var tmat = Bone._tmpMats[0];
  70034. var vec = Bone._tmpVecs[0];
  70035. if (this._parent) {
  70036. if (mesh && wm) {
  70037. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70038. tmat.multiplyToRef(wm, tmat);
  70039. }
  70040. else {
  70041. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70042. }
  70043. }
  70044. tmat.invert();
  70045. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  70046. lm.m[12] = vec.x;
  70047. lm.m[13] = vec.y;
  70048. lm.m[14] = vec.z;
  70049. }
  70050. this.markAsDirty();
  70051. };
  70052. /**
  70053. * Set the absolute postion of the bone (world space).
  70054. * @param position The position to set the bone.
  70055. * @param mesh The mesh that this bone is attached to.
  70056. */
  70057. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  70058. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  70059. };
  70060. /**
  70061. * Set the scale of the bone on the x, y and z axes.
  70062. * @param x The scale of the bone on the x axis.
  70063. * @param x The scale of the bone on the y axis.
  70064. * @param z The scale of the bone on the z axis.
  70065. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70066. */
  70067. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  70068. if (scaleChildren === void 0) { scaleChildren = false; }
  70069. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  70070. if (!scaleChildren) {
  70071. this._negateScaleChildren.x = 1 / x;
  70072. this._negateScaleChildren.y = 1 / y;
  70073. this._negateScaleChildren.z = 1 / z;
  70074. }
  70075. this._syncScaleVector();
  70076. }
  70077. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  70078. };
  70079. /**
  70080. * Scale the bone on the x, y and z axes.
  70081. * @param x The amount to scale the bone on the x axis.
  70082. * @param x The amount to scale the bone on the y axis.
  70083. * @param z The amount to scale the bone on the z axis.
  70084. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70085. */
  70086. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  70087. if (scaleChildren === void 0) { scaleChildren = false; }
  70088. var locMat = this.getLocalMatrix();
  70089. var origLocMat = Bone._tmpMats[0];
  70090. origLocMat.copyFrom(locMat);
  70091. var origLocMatInv = Bone._tmpMats[1];
  70092. origLocMatInv.copyFrom(origLocMat);
  70093. origLocMatInv.invert();
  70094. var scaleMat = Bone._tmpMats[2];
  70095. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  70096. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  70097. this._scaleVector.x *= x;
  70098. this._scaleVector.y *= y;
  70099. this._scaleVector.z *= z;
  70100. locMat.multiplyToRef(origLocMatInv, locMat);
  70101. locMat.multiplyToRef(scaleMat, locMat);
  70102. locMat.multiplyToRef(origLocMat, locMat);
  70103. var parent = this.getParent();
  70104. if (parent) {
  70105. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  70106. }
  70107. else {
  70108. this.getAbsoluteTransform().copyFrom(locMat);
  70109. }
  70110. var len = this.children.length;
  70111. scaleMat.invert();
  70112. for (var i = 0; i < len; i++) {
  70113. var child = this.children[i];
  70114. var cm = child.getLocalMatrix();
  70115. cm.multiplyToRef(scaleMat, cm);
  70116. var lm = child.getLocalMatrix();
  70117. lm.m[12] *= x;
  70118. lm.m[13] *= y;
  70119. lm.m[14] *= z;
  70120. }
  70121. this.computeAbsoluteTransforms();
  70122. if (scaleChildren) {
  70123. for (var i = 0; i < len; i++) {
  70124. this.children[i].scale(x, y, z, scaleChildren);
  70125. }
  70126. }
  70127. this.markAsDirty();
  70128. };
  70129. /**
  70130. * Set the yaw, pitch, and roll of the bone in local or world space.
  70131. * @param yaw The rotation of the bone on the y axis.
  70132. * @param pitch The rotation of the bone on the x axis.
  70133. * @param roll The rotation of the bone on the z axis.
  70134. * @param space The space that the axes of rotation are in.
  70135. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70136. */
  70137. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  70138. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70139. var rotMat = Bone._tmpMats[0];
  70140. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  70141. var rotMatInv = Bone._tmpMats[1];
  70142. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70143. rotMatInv.multiplyToRef(rotMat, rotMat);
  70144. this._rotateWithMatrix(rotMat, space, mesh);
  70145. };
  70146. /**
  70147. * Rotate the bone on an axis in local or world space.
  70148. * @param axis The axis to rotate the bone on.
  70149. * @param amount The amount to rotate the bone.
  70150. * @param space The space that the axis is in.
  70151. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70152. */
  70153. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  70154. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70155. var rmat = Bone._tmpMats[0];
  70156. rmat.m[12] = 0;
  70157. rmat.m[13] = 0;
  70158. rmat.m[14] = 0;
  70159. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  70160. this._rotateWithMatrix(rmat, space, mesh);
  70161. };
  70162. /**
  70163. * Set the rotation of the bone to a particular axis angle in local or world space.
  70164. * @param axis The axis to rotate the bone on.
  70165. * @param angle The angle that the bone should be rotated to.
  70166. * @param space The space that the axis is in.
  70167. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70168. */
  70169. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  70170. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70171. var rotMat = Bone._tmpMats[0];
  70172. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  70173. var rotMatInv = Bone._tmpMats[1];
  70174. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70175. rotMatInv.multiplyToRef(rotMat, rotMat);
  70176. this._rotateWithMatrix(rotMat, space, mesh);
  70177. };
  70178. /**
  70179. * Set the euler rotation of the bone in local of world space.
  70180. * @param rotation The euler rotation that the bone should be set to.
  70181. * @param space The space that the rotation is in.
  70182. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70183. */
  70184. Bone.prototype.setRotation = function (rotation, space, mesh) {
  70185. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70186. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  70187. };
  70188. /**
  70189. * Set the quaternion rotation of the bone in local of world space.
  70190. * @param quat The quaternion rotation that the bone should be set to.
  70191. * @param space The space that the rotation is in.
  70192. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70193. */
  70194. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  70195. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70196. var rotMatInv = Bone._tmpMats[0];
  70197. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70198. var rotMat = Bone._tmpMats[1];
  70199. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  70200. rotMatInv.multiplyToRef(rotMat, rotMat);
  70201. this._rotateWithMatrix(rotMat, space, mesh);
  70202. };
  70203. /**
  70204. * Set the rotation matrix of the bone in local of world space.
  70205. * @param rotMat The rotation matrix that the bone should be set to.
  70206. * @param space The space that the rotation is in.
  70207. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70208. */
  70209. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  70210. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70211. var rotMatInv = Bone._tmpMats[0];
  70212. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70213. var rotMat2 = Bone._tmpMats[1];
  70214. rotMat2.copyFrom(rotMat);
  70215. rotMatInv.multiplyToRef(rotMat, rotMat2);
  70216. this._rotateWithMatrix(rotMat2, space, mesh);
  70217. };
  70218. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  70219. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70220. var lmat = this.getLocalMatrix();
  70221. var lx = lmat.m[12];
  70222. var ly = lmat.m[13];
  70223. var lz = lmat.m[14];
  70224. var parent = this.getParent();
  70225. var parentScale = Bone._tmpMats[3];
  70226. var parentScaleInv = Bone._tmpMats[4];
  70227. if (parent) {
  70228. if (space == BABYLON.Space.WORLD) {
  70229. if (mesh) {
  70230. parentScale.copyFrom(mesh.getWorldMatrix());
  70231. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  70232. }
  70233. else {
  70234. parentScale.copyFrom(parent.getAbsoluteTransform());
  70235. }
  70236. }
  70237. else {
  70238. parentScale = parent._scaleMatrix;
  70239. }
  70240. parentScaleInv.copyFrom(parentScale);
  70241. parentScaleInv.invert();
  70242. lmat.multiplyToRef(parentScale, lmat);
  70243. lmat.multiplyToRef(rmat, lmat);
  70244. lmat.multiplyToRef(parentScaleInv, lmat);
  70245. }
  70246. else {
  70247. if (space == BABYLON.Space.WORLD && mesh) {
  70248. parentScale.copyFrom(mesh.getWorldMatrix());
  70249. parentScaleInv.copyFrom(parentScale);
  70250. parentScaleInv.invert();
  70251. lmat.multiplyToRef(parentScale, lmat);
  70252. lmat.multiplyToRef(rmat, lmat);
  70253. lmat.multiplyToRef(parentScaleInv, lmat);
  70254. }
  70255. else {
  70256. lmat.multiplyToRef(rmat, lmat);
  70257. }
  70258. }
  70259. lmat.m[12] = lx;
  70260. lmat.m[13] = ly;
  70261. lmat.m[14] = lz;
  70262. this.computeAbsoluteTransforms();
  70263. this.markAsDirty();
  70264. };
  70265. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  70266. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70267. if (space == BABYLON.Space.WORLD) {
  70268. var scaleMatrix = Bone._tmpMats[2];
  70269. scaleMatrix.copyFrom(this._scaleMatrix);
  70270. rotMatInv.copyFrom(this.getAbsoluteTransform());
  70271. if (mesh) {
  70272. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  70273. var meshScale = Bone._tmpMats[3];
  70274. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  70275. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  70276. }
  70277. rotMatInv.invert();
  70278. scaleMatrix.m[0] *= this._scalingDeterminant;
  70279. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70280. }
  70281. else {
  70282. rotMatInv.copyFrom(this.getLocalMatrix());
  70283. rotMatInv.invert();
  70284. var scaleMatrix = Bone._tmpMats[2];
  70285. scaleMatrix.copyFrom(this._scaleMatrix);
  70286. if (this._parent) {
  70287. var pscaleMatrix = Bone._tmpMats[3];
  70288. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  70289. pscaleMatrix.invert();
  70290. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  70291. }
  70292. else {
  70293. scaleMatrix.m[0] *= this._scalingDeterminant;
  70294. }
  70295. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70296. }
  70297. };
  70298. /**
  70299. * Get the scale of the bone
  70300. * @returns the scale of the bone
  70301. */
  70302. Bone.prototype.getScale = function () {
  70303. return this._scaleVector.clone();
  70304. };
  70305. /**
  70306. * Copy the scale of the bone to a vector3.
  70307. * @param result The vector3 to copy the scale to
  70308. */
  70309. Bone.prototype.getScaleToRef = function (result) {
  70310. result.copyFrom(this._scaleVector);
  70311. };
  70312. /**
  70313. * Get the position of the bone in local or world space.
  70314. * @param space The space that the returned position is in.
  70315. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70316. * @returns The position of the bone
  70317. */
  70318. Bone.prototype.getPosition = function (space, mesh) {
  70319. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70320. if (mesh === void 0) { mesh = null; }
  70321. var pos = BABYLON.Vector3.Zero();
  70322. this.getPositionToRef(space, mesh, pos);
  70323. return pos;
  70324. };
  70325. /**
  70326. * Copy the position of the bone to a vector3 in local or world space.
  70327. * @param space The space that the returned position is in.
  70328. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70329. * @param result The vector3 to copy the position to.
  70330. */
  70331. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  70332. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70333. if (space == BABYLON.Space.LOCAL) {
  70334. var lm = this.getLocalMatrix();
  70335. result.x = lm.m[12];
  70336. result.y = lm.m[13];
  70337. result.z = lm.m[14];
  70338. }
  70339. else {
  70340. var wm = null;
  70341. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70342. if (mesh) {
  70343. wm = mesh.getWorldMatrix();
  70344. }
  70345. this._skeleton.computeAbsoluteTransforms();
  70346. var tmat = Bone._tmpMats[0];
  70347. if (mesh && wm) {
  70348. tmat.copyFrom(this.getAbsoluteTransform());
  70349. tmat.multiplyToRef(wm, tmat);
  70350. }
  70351. else {
  70352. tmat = this.getAbsoluteTransform();
  70353. }
  70354. result.x = tmat.m[12];
  70355. result.y = tmat.m[13];
  70356. result.z = tmat.m[14];
  70357. }
  70358. };
  70359. /**
  70360. * Get the absolute position of the bone (world space).
  70361. * @param mesh The mesh that this bone is attached to.
  70362. * @returns The absolute position of the bone
  70363. */
  70364. Bone.prototype.getAbsolutePosition = function (mesh) {
  70365. if (mesh === void 0) { mesh = null; }
  70366. var pos = BABYLON.Vector3.Zero();
  70367. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  70368. return pos;
  70369. };
  70370. /**
  70371. * Copy the absolute position of the bone (world space) to the result param.
  70372. * @param mesh The mesh that this bone is attached to.
  70373. * @param result The vector3 to copy the absolute position to.
  70374. */
  70375. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  70376. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  70377. };
  70378. /**
  70379. * Compute the absolute transforms of this bone and its children.
  70380. */
  70381. Bone.prototype.computeAbsoluteTransforms = function () {
  70382. if (this._parent) {
  70383. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70384. }
  70385. else {
  70386. this._absoluteTransform.copyFrom(this._localMatrix);
  70387. var poseMatrix = this._skeleton.getPoseMatrix();
  70388. if (poseMatrix) {
  70389. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  70390. }
  70391. }
  70392. var children = this.children;
  70393. var len = children.length;
  70394. for (var i = 0; i < len; i++) {
  70395. children[i].computeAbsoluteTransforms();
  70396. }
  70397. };
  70398. Bone.prototype._syncScaleVector = function () {
  70399. var lm = this.getLocalMatrix();
  70400. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  70401. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  70402. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  70403. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  70404. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  70405. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  70406. this._scaleVector.x = xs * Math.sqrt(xsq);
  70407. this._scaleVector.y = ys * Math.sqrt(ysq);
  70408. this._scaleVector.z = zs * Math.sqrt(zsq);
  70409. if (this._parent) {
  70410. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  70411. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  70412. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  70413. }
  70414. 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);
  70415. };
  70416. /**
  70417. * Get the world direction from an axis that is in the local space of the bone.
  70418. * @param localAxis The local direction that is used to compute the world direction.
  70419. * @param mesh The mesh that this bone is attached to.
  70420. * @returns The world direction
  70421. */
  70422. Bone.prototype.getDirection = function (localAxis, mesh) {
  70423. if (mesh === void 0) { mesh = null; }
  70424. var result = BABYLON.Vector3.Zero();
  70425. this.getDirectionToRef(localAxis, mesh, result);
  70426. return result;
  70427. };
  70428. /**
  70429. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  70430. * @param localAxis The local direction that is used to compute the world direction.
  70431. * @param mesh The mesh that this bone is attached to.
  70432. * @param result The vector3 that the world direction will be copied to.
  70433. */
  70434. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  70435. if (mesh === void 0) { mesh = null; }
  70436. var wm = null;
  70437. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70438. if (mesh) {
  70439. wm = mesh.getWorldMatrix();
  70440. }
  70441. this._skeleton.computeAbsoluteTransforms();
  70442. var mat = Bone._tmpMats[0];
  70443. mat.copyFrom(this.getAbsoluteTransform());
  70444. if (mesh && wm) {
  70445. mat.multiplyToRef(wm, mat);
  70446. }
  70447. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  70448. result.normalize();
  70449. };
  70450. /**
  70451. * Get the euler rotation of the bone in local or world space.
  70452. * @param space The space that the rotation should be in.
  70453. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70454. * @returns The euler rotation
  70455. */
  70456. Bone.prototype.getRotation = function (space, mesh) {
  70457. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70458. if (mesh === void 0) { mesh = null; }
  70459. var result = BABYLON.Vector3.Zero();
  70460. this.getRotationToRef(space, mesh, result);
  70461. return result;
  70462. };
  70463. /**
  70464. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  70465. * @param space The space that the rotation should be in.
  70466. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70467. * @param result The vector3 that the rotation should be copied to.
  70468. */
  70469. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  70470. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70471. if (mesh === void 0) { mesh = null; }
  70472. var quat = Bone._tmpQuat;
  70473. this.getRotationQuaternionToRef(space, mesh, quat);
  70474. quat.toEulerAnglesToRef(result);
  70475. };
  70476. /**
  70477. * Get the quaternion rotation of the bone in either local or world space.
  70478. * @param space The space that the rotation should be in.
  70479. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70480. * @returns The quaternion rotation
  70481. */
  70482. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  70483. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70484. if (mesh === void 0) { mesh = null; }
  70485. var result = BABYLON.Quaternion.Identity();
  70486. this.getRotationQuaternionToRef(space, mesh, result);
  70487. return result;
  70488. };
  70489. /**
  70490. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  70491. * @param space The space that the rotation should be in.
  70492. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70493. * @param result The quaternion that the rotation should be copied to.
  70494. */
  70495. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  70496. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70497. if (mesh === void 0) { mesh = null; }
  70498. if (space == BABYLON.Space.LOCAL) {
  70499. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70500. }
  70501. else {
  70502. var mat = Bone._tmpMats[0];
  70503. var amat = this.getAbsoluteTransform();
  70504. if (mesh) {
  70505. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70506. }
  70507. else {
  70508. mat.copyFrom(amat);
  70509. }
  70510. mat.m[0] *= this._scalingDeterminant;
  70511. mat.m[1] *= this._scalingDeterminant;
  70512. mat.m[2] *= this._scalingDeterminant;
  70513. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70514. }
  70515. };
  70516. /**
  70517. * Get the rotation matrix of the bone in local or world space.
  70518. * @param space The space that the rotation should be in.
  70519. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70520. * @returns The rotation matrix
  70521. */
  70522. Bone.prototype.getRotationMatrix = function (space, mesh) {
  70523. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70524. var result = BABYLON.Matrix.Identity();
  70525. this.getRotationMatrixToRef(space, mesh, result);
  70526. return result;
  70527. };
  70528. /**
  70529. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  70530. * @param space The space that the rotation should be in.
  70531. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70532. * @param result The quaternion that the rotation should be copied to.
  70533. */
  70534. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  70535. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70536. if (space == BABYLON.Space.LOCAL) {
  70537. this.getLocalMatrix().getRotationMatrixToRef(result);
  70538. }
  70539. else {
  70540. var mat = Bone._tmpMats[0];
  70541. var amat = this.getAbsoluteTransform();
  70542. if (mesh) {
  70543. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70544. }
  70545. else {
  70546. mat.copyFrom(amat);
  70547. }
  70548. mat.m[0] *= this._scalingDeterminant;
  70549. mat.m[1] *= this._scalingDeterminant;
  70550. mat.m[2] *= this._scalingDeterminant;
  70551. mat.getRotationMatrixToRef(result);
  70552. }
  70553. };
  70554. /**
  70555. * Get the world position of a point that is in the local space of the bone.
  70556. * @param position The local position
  70557. * @param mesh The mesh that this bone is attached to.
  70558. * @returns The world position
  70559. */
  70560. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  70561. if (mesh === void 0) { mesh = null; }
  70562. var result = BABYLON.Vector3.Zero();
  70563. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  70564. return result;
  70565. };
  70566. /**
  70567. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  70568. * @param position The local position
  70569. * @param mesh The mesh that this bone is attached to.
  70570. * @param result The vector3 that the world position should be copied to.
  70571. */
  70572. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  70573. if (mesh === void 0) { mesh = null; }
  70574. var wm = null;
  70575. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70576. if (mesh) {
  70577. wm = mesh.getWorldMatrix();
  70578. }
  70579. this._skeleton.computeAbsoluteTransforms();
  70580. var tmat = Bone._tmpMats[0];
  70581. if (mesh && wm) {
  70582. tmat.copyFrom(this.getAbsoluteTransform());
  70583. tmat.multiplyToRef(wm, tmat);
  70584. }
  70585. else {
  70586. tmat = this.getAbsoluteTransform();
  70587. }
  70588. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70589. };
  70590. /**
  70591. * Get the local position of a point that is in world space.
  70592. * @param position The world position
  70593. * @param mesh The mesh that this bone is attached to.
  70594. * @returns The local position
  70595. */
  70596. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  70597. if (mesh === void 0) { mesh = null; }
  70598. var result = BABYLON.Vector3.Zero();
  70599. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  70600. return result;
  70601. };
  70602. /**
  70603. * Get the local position of a point that is in world space and copy it to the result param.
  70604. * @param position The world position
  70605. * @param mesh The mesh that this bone is attached to.
  70606. * @param result The vector3 that the local position should be copied to.
  70607. */
  70608. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  70609. if (mesh === void 0) { mesh = null; }
  70610. var wm = null;
  70611. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70612. if (mesh) {
  70613. wm = mesh.getWorldMatrix();
  70614. }
  70615. this._skeleton.computeAbsoluteTransforms();
  70616. var tmat = Bone._tmpMats[0];
  70617. tmat.copyFrom(this.getAbsoluteTransform());
  70618. if (mesh && wm) {
  70619. tmat.multiplyToRef(wm, tmat);
  70620. }
  70621. tmat.invert();
  70622. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70623. };
  70624. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70625. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  70626. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70627. return Bone;
  70628. }(BABYLON.Node));
  70629. BABYLON.Bone = Bone;
  70630. })(BABYLON || (BABYLON = {}));
  70631. //# sourceMappingURL=babylon.bone.js.map
  70632. var BABYLON;
  70633. (function (BABYLON) {
  70634. var BoneIKController = /** @class */ (function () {
  70635. function BoneIKController(mesh, bone, options) {
  70636. this.targetPosition = BABYLON.Vector3.Zero();
  70637. this.poleTargetPosition = BABYLON.Vector3.Zero();
  70638. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  70639. this.poleAngle = 0;
  70640. this.slerpAmount = 1;
  70641. this._bone1Quat = BABYLON.Quaternion.Identity();
  70642. this._bone1Mat = BABYLON.Matrix.Identity();
  70643. this._bone2Ang = Math.PI;
  70644. this._maxAngle = Math.PI;
  70645. this._rightHandedSystem = false;
  70646. this._bendAxis = BABYLON.Vector3.Right();
  70647. this._slerping = false;
  70648. this._adjustRoll = 0;
  70649. this._bone2 = bone;
  70650. this._bone1 = bone.getParent();
  70651. if (!this._bone1) {
  70652. return;
  70653. }
  70654. this.mesh = mesh;
  70655. var bonePos = bone.getPosition();
  70656. if (bone.getAbsoluteTransform().determinant() > 0) {
  70657. this._rightHandedSystem = true;
  70658. this._bendAxis.x = 0;
  70659. this._bendAxis.y = 0;
  70660. this._bendAxis.z = -1;
  70661. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  70662. this._adjustRoll = Math.PI * .5;
  70663. this._bendAxis.z = 1;
  70664. }
  70665. }
  70666. if (this._bone1.length) {
  70667. var boneScale1 = this._bone1.getScale();
  70668. var boneScale2 = this._bone2.getScale();
  70669. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  70670. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  70671. }
  70672. else if (this._bone1.children[0]) {
  70673. mesh.computeWorldMatrix(true);
  70674. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  70675. var pos2 = this._bone2.getAbsolutePosition(mesh);
  70676. var pos3 = this._bone1.getAbsolutePosition(mesh);
  70677. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  70678. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  70679. }
  70680. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  70681. this.maxAngle = Math.PI;
  70682. if (options) {
  70683. if (options.targetMesh) {
  70684. this.targetMesh = options.targetMesh;
  70685. this.targetMesh.computeWorldMatrix(true);
  70686. }
  70687. if (options.poleTargetMesh) {
  70688. this.poleTargetMesh = options.poleTargetMesh;
  70689. this.poleTargetMesh.computeWorldMatrix(true);
  70690. }
  70691. else if (options.poleTargetBone) {
  70692. this.poleTargetBone = options.poleTargetBone;
  70693. }
  70694. else if (this._bone1.getParent()) {
  70695. this.poleTargetBone = this._bone1.getParent();
  70696. }
  70697. if (options.poleTargetLocalOffset) {
  70698. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  70699. }
  70700. if (options.poleAngle) {
  70701. this.poleAngle = options.poleAngle;
  70702. }
  70703. if (options.bendAxis) {
  70704. this._bendAxis.copyFrom(options.bendAxis);
  70705. }
  70706. if (options.maxAngle) {
  70707. this.maxAngle = options.maxAngle;
  70708. }
  70709. if (options.slerpAmount) {
  70710. this.slerpAmount = options.slerpAmount;
  70711. }
  70712. }
  70713. }
  70714. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  70715. get: function () {
  70716. return this._maxAngle;
  70717. },
  70718. set: function (value) {
  70719. this._setMaxAngle(value);
  70720. },
  70721. enumerable: true,
  70722. configurable: true
  70723. });
  70724. BoneIKController.prototype._setMaxAngle = function (ang) {
  70725. if (ang < 0) {
  70726. ang = 0;
  70727. }
  70728. if (ang > Math.PI || ang == undefined) {
  70729. ang = Math.PI;
  70730. }
  70731. this._maxAngle = ang;
  70732. var a = this._bone1Length;
  70733. var b = this._bone2Length;
  70734. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  70735. };
  70736. BoneIKController.prototype.update = function () {
  70737. var bone1 = this._bone1;
  70738. if (!bone1) {
  70739. return;
  70740. }
  70741. var target = this.targetPosition;
  70742. var poleTarget = this.poleTargetPosition;
  70743. var mat1 = BoneIKController._tmpMats[0];
  70744. var mat2 = BoneIKController._tmpMats[1];
  70745. if (this.targetMesh) {
  70746. target.copyFrom(this.targetMesh.getAbsolutePosition());
  70747. }
  70748. if (this.poleTargetBone) {
  70749. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  70750. }
  70751. else if (this.poleTargetMesh) {
  70752. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  70753. }
  70754. var bonePos = BoneIKController._tmpVecs[0];
  70755. var zaxis = BoneIKController._tmpVecs[1];
  70756. var xaxis = BoneIKController._tmpVecs[2];
  70757. var yaxis = BoneIKController._tmpVecs[3];
  70758. var upAxis = BoneIKController._tmpVecs[4];
  70759. var _tmpQuat = BoneIKController._tmpQuat;
  70760. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  70761. poleTarget.subtractToRef(bonePos, upAxis);
  70762. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  70763. upAxis.y = 1;
  70764. }
  70765. else {
  70766. upAxis.normalize();
  70767. }
  70768. target.subtractToRef(bonePos, yaxis);
  70769. yaxis.normalize();
  70770. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  70771. zaxis.normalize();
  70772. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  70773. xaxis.normalize();
  70774. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  70775. var a = this._bone1Length;
  70776. var b = this._bone2Length;
  70777. var c = BABYLON.Vector3.Distance(bonePos, target);
  70778. if (this._maxReach > 0) {
  70779. c = Math.min(this._maxReach, c);
  70780. }
  70781. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  70782. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  70783. if (acosa > 1) {
  70784. acosa = 1;
  70785. }
  70786. if (acosb > 1) {
  70787. acosb = 1;
  70788. }
  70789. if (acosa < -1) {
  70790. acosa = -1;
  70791. }
  70792. if (acosb < -1) {
  70793. acosb = -1;
  70794. }
  70795. var angA = Math.acos(acosa);
  70796. var angB = Math.acos(acosb);
  70797. var angC = -angA - angB;
  70798. if (this._rightHandedSystem) {
  70799. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  70800. mat2.multiplyToRef(mat1, mat1);
  70801. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  70802. mat2.multiplyToRef(mat1, mat1);
  70803. }
  70804. else {
  70805. var _tmpVec = BoneIKController._tmpVecs[5];
  70806. _tmpVec.copyFrom(this._bendAxis);
  70807. _tmpVec.x *= -1;
  70808. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  70809. mat2.multiplyToRef(mat1, mat1);
  70810. }
  70811. if (this.poleAngle) {
  70812. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  70813. mat1.multiplyToRef(mat2, mat1);
  70814. }
  70815. if (this._bone1) {
  70816. if (this.slerpAmount < 1) {
  70817. if (!this._slerping) {
  70818. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  70819. }
  70820. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  70821. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  70822. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  70823. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  70824. this._slerping = true;
  70825. }
  70826. else {
  70827. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  70828. this._bone1Mat.copyFrom(mat1);
  70829. this._slerping = false;
  70830. }
  70831. }
  70832. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  70833. this._bone2Ang = angC;
  70834. };
  70835. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70836. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  70837. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70838. return BoneIKController;
  70839. }());
  70840. BABYLON.BoneIKController = BoneIKController;
  70841. })(BABYLON || (BABYLON = {}));
  70842. //# sourceMappingURL=babylon.boneIKController.js.map
  70843. var BABYLON;
  70844. (function (BABYLON) {
  70845. var BoneLookController = /** @class */ (function () {
  70846. /**
  70847. * Create a BoneLookController
  70848. * @param mesh the mesh that the bone belongs to
  70849. * @param bone the bone that will be looking to the target
  70850. * @param target the target Vector3 to look at
  70851. * @param settings optional settings:
  70852. * - maxYaw: the maximum angle the bone will yaw to
  70853. * - minYaw: the minimum angle the bone will yaw to
  70854. * - maxPitch: the maximum angle the bone will pitch to
  70855. * - minPitch: the minimum angle the bone will yaw to
  70856. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  70857. * - upAxis: the up axis of the coordinate system
  70858. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  70859. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  70860. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  70861. * - adjustYaw: used to make an adjustment to the yaw of the bone
  70862. * - adjustPitch: used to make an adjustment to the pitch of the bone
  70863. * - adjustRoll: used to make an adjustment to the roll of the bone
  70864. **/
  70865. function BoneLookController(mesh, bone, target, options) {
  70866. /**
  70867. * The up axis of the coordinate system that is used when the bone is rotated.
  70868. */
  70869. this.upAxis = BABYLON.Vector3.Up();
  70870. /**
  70871. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  70872. */
  70873. this.upAxisSpace = BABYLON.Space.LOCAL;
  70874. /**
  70875. * Used to make an adjustment to the yaw of the bone.
  70876. */
  70877. this.adjustYaw = 0;
  70878. /**
  70879. * Used to make an adjustment to the pitch of the bone.
  70880. */
  70881. this.adjustPitch = 0;
  70882. /**
  70883. * Used to make an adjustment to the roll of the bone.
  70884. */
  70885. this.adjustRoll = 0;
  70886. /**
  70887. * 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).
  70888. */
  70889. this.slerpAmount = 1;
  70890. this._boneQuat = BABYLON.Quaternion.Identity();
  70891. this._slerping = false;
  70892. this._firstFrameSkipped = false;
  70893. this._fowardAxis = BABYLON.Vector3.Forward();
  70894. this.mesh = mesh;
  70895. this.bone = bone;
  70896. this.target = target;
  70897. if (options) {
  70898. if (options.adjustYaw) {
  70899. this.adjustYaw = options.adjustYaw;
  70900. }
  70901. if (options.adjustPitch) {
  70902. this.adjustPitch = options.adjustPitch;
  70903. }
  70904. if (options.adjustRoll) {
  70905. this.adjustRoll = options.adjustRoll;
  70906. }
  70907. if (options.maxYaw != null) {
  70908. this.maxYaw = options.maxYaw;
  70909. }
  70910. else {
  70911. this.maxYaw = Math.PI;
  70912. }
  70913. if (options.minYaw != null) {
  70914. this.minYaw = options.minYaw;
  70915. }
  70916. else {
  70917. this.minYaw = -Math.PI;
  70918. }
  70919. if (options.maxPitch != null) {
  70920. this.maxPitch = options.maxPitch;
  70921. }
  70922. else {
  70923. this.maxPitch = Math.PI;
  70924. }
  70925. if (options.minPitch != null) {
  70926. this.minPitch = options.minPitch;
  70927. }
  70928. else {
  70929. this.minPitch = -Math.PI;
  70930. }
  70931. if (options.slerpAmount != null) {
  70932. this.slerpAmount = options.slerpAmount;
  70933. }
  70934. if (options.upAxis != null) {
  70935. this.upAxis = options.upAxis;
  70936. }
  70937. if (options.upAxisSpace != null) {
  70938. this.upAxisSpace = options.upAxisSpace;
  70939. }
  70940. if (options.yawAxis != null || options.pitchAxis != null) {
  70941. var newYawAxis = BABYLON.Axis.Y;
  70942. var newPitchAxis = BABYLON.Axis.X;
  70943. if (options.yawAxis != null) {
  70944. newYawAxis = options.yawAxis.clone();
  70945. newYawAxis.normalize();
  70946. }
  70947. if (options.pitchAxis != null) {
  70948. newPitchAxis = options.pitchAxis.clone();
  70949. newPitchAxis.normalize();
  70950. }
  70951. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  70952. this._transformYawPitch = BABYLON.Matrix.Identity();
  70953. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  70954. this._transformYawPitchInv = this._transformYawPitch.clone();
  70955. this._transformYawPitch.invert();
  70956. }
  70957. }
  70958. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  70959. this.upAxisSpace = BABYLON.Space.LOCAL;
  70960. }
  70961. }
  70962. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  70963. /**
  70964. * Get/set the minimum yaw angle that the bone can look to.
  70965. */
  70966. get: function () {
  70967. return this._minYaw;
  70968. },
  70969. set: function (value) {
  70970. this._minYaw = value;
  70971. this._minYawSin = Math.sin(value);
  70972. this._minYawCos = Math.cos(value);
  70973. if (this._maxYaw != null) {
  70974. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  70975. this._yawRange = this._maxYaw - this._minYaw;
  70976. }
  70977. },
  70978. enumerable: true,
  70979. configurable: true
  70980. });
  70981. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  70982. /**
  70983. * Get/set the maximum yaw angle that the bone can look to.
  70984. */
  70985. get: function () {
  70986. return this._maxYaw;
  70987. },
  70988. set: function (value) {
  70989. this._maxYaw = value;
  70990. this._maxYawSin = Math.sin(value);
  70991. this._maxYawCos = Math.cos(value);
  70992. if (this._minYaw != null) {
  70993. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  70994. this._yawRange = this._maxYaw - this._minYaw;
  70995. }
  70996. },
  70997. enumerable: true,
  70998. configurable: true
  70999. });
  71000. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  71001. /**
  71002. * Get/set the minimum pitch angle that the bone can look to.
  71003. */
  71004. get: function () {
  71005. return this._minPitch;
  71006. },
  71007. set: function (value) {
  71008. this._minPitch = value;
  71009. this._minPitchTan = Math.tan(value);
  71010. },
  71011. enumerable: true,
  71012. configurable: true
  71013. });
  71014. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  71015. /**
  71016. * Get/set the maximum pitch angle that the bone can look to.
  71017. */
  71018. get: function () {
  71019. return this._maxPitch;
  71020. },
  71021. set: function (value) {
  71022. this._maxPitch = value;
  71023. this._maxPitchTan = Math.tan(value);
  71024. },
  71025. enumerable: true,
  71026. configurable: true
  71027. });
  71028. /**
  71029. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  71030. */
  71031. BoneLookController.prototype.update = function () {
  71032. //skip the first frame when slerping so that the mesh rotation is correct
  71033. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  71034. this._firstFrameSkipped = true;
  71035. return;
  71036. }
  71037. var bone = this.bone;
  71038. var bonePos = BoneLookController._tmpVecs[0];
  71039. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  71040. var target = this.target;
  71041. var _tmpMat1 = BoneLookController._tmpMats[0];
  71042. var _tmpMat2 = BoneLookController._tmpMats[1];
  71043. var mesh = this.mesh;
  71044. var parentBone = bone.getParent();
  71045. var upAxis = BoneLookController._tmpVecs[1];
  71046. upAxis.copyFrom(this.upAxis);
  71047. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  71048. if (this._transformYawPitch) {
  71049. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  71050. }
  71051. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  71052. }
  71053. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  71054. mesh.getDirectionToRef(upAxis, upAxis);
  71055. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  71056. upAxis.normalize();
  71057. }
  71058. }
  71059. var checkYaw = false;
  71060. var checkPitch = false;
  71061. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  71062. checkYaw = true;
  71063. }
  71064. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  71065. checkPitch = true;
  71066. }
  71067. if (checkYaw || checkPitch) {
  71068. var spaceMat = BoneLookController._tmpMats[2];
  71069. var spaceMatInv = BoneLookController._tmpMats[3];
  71070. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  71071. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  71072. }
  71073. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  71074. spaceMat.copyFrom(mesh.getWorldMatrix());
  71075. }
  71076. else {
  71077. var forwardAxis = BoneLookController._tmpVecs[2];
  71078. forwardAxis.copyFrom(this._fowardAxis);
  71079. if (this._transformYawPitch) {
  71080. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  71081. }
  71082. if (parentBone) {
  71083. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  71084. }
  71085. else {
  71086. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  71087. }
  71088. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  71089. rightAxis.normalize();
  71090. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  71091. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  71092. }
  71093. spaceMat.invertToRef(spaceMatInv);
  71094. var xzlen = null;
  71095. if (checkPitch) {
  71096. var localTarget = BoneLookController._tmpVecs[3];
  71097. target.subtractToRef(bonePos, localTarget);
  71098. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71099. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71100. var pitch = Math.atan2(localTarget.y, xzlen);
  71101. var newPitch = pitch;
  71102. if (pitch > this._maxPitch) {
  71103. localTarget.y = this._maxPitchTan * xzlen;
  71104. newPitch = this._maxPitch;
  71105. }
  71106. else if (pitch < this._minPitch) {
  71107. localTarget.y = this._minPitchTan * xzlen;
  71108. newPitch = this._minPitch;
  71109. }
  71110. if (pitch != newPitch) {
  71111. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71112. localTarget.addInPlace(bonePos);
  71113. target = localTarget;
  71114. }
  71115. }
  71116. if (checkYaw) {
  71117. var localTarget = BoneLookController._tmpVecs[4];
  71118. target.subtractToRef(bonePos, localTarget);
  71119. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71120. var yaw = Math.atan2(localTarget.x, localTarget.z);
  71121. var newYaw = yaw;
  71122. if (yaw > this._maxYaw || yaw < this._minYaw) {
  71123. if (xzlen == null) {
  71124. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71125. }
  71126. if (this._yawRange > Math.PI) {
  71127. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  71128. localTarget.z = this._maxYawCos * xzlen;
  71129. localTarget.x = this._maxYawSin * xzlen;
  71130. newYaw = this._maxYaw;
  71131. }
  71132. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  71133. localTarget.z = this._minYawCos * xzlen;
  71134. localTarget.x = this._minYawSin * xzlen;
  71135. newYaw = this._minYaw;
  71136. }
  71137. }
  71138. else {
  71139. if (yaw > this._maxYaw) {
  71140. localTarget.z = this._maxYawCos * xzlen;
  71141. localTarget.x = this._maxYawSin * xzlen;
  71142. newYaw = this._maxYaw;
  71143. }
  71144. else if (yaw < this._minYaw) {
  71145. localTarget.z = this._minYawCos * xzlen;
  71146. localTarget.x = this._minYawSin * xzlen;
  71147. newYaw = this._minYaw;
  71148. }
  71149. }
  71150. }
  71151. if (this._slerping && this._yawRange > Math.PI) {
  71152. //are we going to be crossing into the min/max region?
  71153. var boneFwd = BoneLookController._tmpVecs[8];
  71154. boneFwd.copyFrom(BABYLON.Axis.Z);
  71155. if (this._transformYawPitch) {
  71156. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  71157. }
  71158. var boneRotMat = BoneLookController._tmpMats[4];
  71159. this._boneQuat.toRotationMatrix(boneRotMat);
  71160. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  71161. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  71162. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  71163. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  71164. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  71165. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  71166. if (angBtwTar > angBtwMidYaw) {
  71167. if (xzlen == null) {
  71168. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71169. }
  71170. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  71171. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  71172. if (angBtwMin < angBtwMax) {
  71173. newYaw = boneYaw + Math.PI * .75;
  71174. localTarget.z = Math.cos(newYaw) * xzlen;
  71175. localTarget.x = Math.sin(newYaw) * xzlen;
  71176. }
  71177. else {
  71178. newYaw = boneYaw - Math.PI * .75;
  71179. localTarget.z = Math.cos(newYaw) * xzlen;
  71180. localTarget.x = Math.sin(newYaw) * xzlen;
  71181. }
  71182. }
  71183. }
  71184. if (yaw != newYaw) {
  71185. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71186. localTarget.addInPlace(bonePos);
  71187. target = localTarget;
  71188. }
  71189. }
  71190. }
  71191. var zaxis = BoneLookController._tmpVecs[5];
  71192. var xaxis = BoneLookController._tmpVecs[6];
  71193. var yaxis = BoneLookController._tmpVecs[7];
  71194. var _tmpQuat = BoneLookController._tmpQuat;
  71195. target.subtractToRef(bonePos, zaxis);
  71196. zaxis.normalize();
  71197. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  71198. xaxis.normalize();
  71199. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  71200. yaxis.normalize();
  71201. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  71202. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  71203. return;
  71204. }
  71205. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  71206. return;
  71207. }
  71208. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  71209. return;
  71210. }
  71211. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  71212. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  71213. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  71214. }
  71215. if (this.slerpAmount < 1) {
  71216. if (!this._slerping) {
  71217. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  71218. }
  71219. if (this._transformYawPitch) {
  71220. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71221. }
  71222. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  71223. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  71224. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  71225. this._slerping = true;
  71226. }
  71227. else {
  71228. if (this._transformYawPitch) {
  71229. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71230. }
  71231. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  71232. this._slerping = false;
  71233. }
  71234. };
  71235. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  71236. var angDiff = ang2 - ang1;
  71237. angDiff %= Math.PI * 2;
  71238. if (angDiff > Math.PI) {
  71239. angDiff -= Math.PI * 2;
  71240. }
  71241. else if (angDiff < -Math.PI) {
  71242. angDiff += Math.PI * 2;
  71243. }
  71244. return angDiff;
  71245. };
  71246. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  71247. ang1 %= (2 * Math.PI);
  71248. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71249. ang2 %= (2 * Math.PI);
  71250. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71251. var ab = 0;
  71252. if (ang1 < ang2) {
  71253. ab = ang2 - ang1;
  71254. }
  71255. else {
  71256. ab = ang1 - ang2;
  71257. }
  71258. if (ab > Math.PI) {
  71259. ab = Math.PI * 2 - ab;
  71260. }
  71261. return ab;
  71262. };
  71263. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  71264. ang %= (2 * Math.PI);
  71265. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  71266. ang1 %= (2 * Math.PI);
  71267. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71268. ang2 %= (2 * Math.PI);
  71269. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71270. if (ang1 < ang2) {
  71271. if (ang > ang1 && ang < ang2) {
  71272. return true;
  71273. }
  71274. }
  71275. else {
  71276. if (ang > ang2 && ang < ang1) {
  71277. return true;
  71278. }
  71279. }
  71280. return false;
  71281. };
  71282. 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()];
  71283. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  71284. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71285. return BoneLookController;
  71286. }());
  71287. BABYLON.BoneLookController = BoneLookController;
  71288. })(BABYLON || (BABYLON = {}));
  71289. //# sourceMappingURL=babylon.boneLookController.js.map
  71290. var BABYLON;
  71291. (function (BABYLON) {
  71292. var Skeleton = /** @class */ (function () {
  71293. function Skeleton(name, id, scene) {
  71294. this.name = name;
  71295. this.id = id;
  71296. this.bones = new Array();
  71297. this.needInitialSkinMatrix = false;
  71298. this._isDirty = true;
  71299. this._meshesWithPoseMatrix = new Array();
  71300. this._identity = BABYLON.Matrix.Identity();
  71301. this._ranges = {};
  71302. this._lastAbsoluteTransformsUpdateId = -1;
  71303. /**
  71304. * Specifies if the skeleton should be serialized.
  71305. */
  71306. this.doNotSerialize = false;
  71307. // Events
  71308. /**
  71309. * An event triggered before computing the skeleton's matrices
  71310. * @type {BABYLON.Observable}
  71311. */
  71312. this.onBeforeComputeObservable = new BABYLON.Observable();
  71313. this.bones = [];
  71314. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71315. scene.skeletons.push(this);
  71316. //make sure it will recalculate the matrix next time prepare is called.
  71317. this._isDirty = true;
  71318. }
  71319. // Members
  71320. Skeleton.prototype.getTransformMatrices = function (mesh) {
  71321. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  71322. return mesh._bonesTransformMatrices;
  71323. }
  71324. if (!this._transformMatrices) {
  71325. this.prepare();
  71326. }
  71327. return this._transformMatrices;
  71328. };
  71329. Skeleton.prototype.getScene = function () {
  71330. return this._scene;
  71331. };
  71332. // Methods
  71333. /**
  71334. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  71335. */
  71336. Skeleton.prototype.toString = function (fullDetails) {
  71337. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  71338. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  71339. if (fullDetails) {
  71340. ret += ", Ranges: {";
  71341. var first = true;
  71342. for (var name_1 in this._ranges) {
  71343. if (first) {
  71344. ret += ", ";
  71345. first = false;
  71346. }
  71347. ret += name_1;
  71348. }
  71349. ret += "}";
  71350. }
  71351. return ret;
  71352. };
  71353. /**
  71354. * Get bone's index searching by name
  71355. * @param {string} name is bone's name to search for
  71356. * @return {number} Indice of the bone. Returns -1 if not found
  71357. */
  71358. Skeleton.prototype.getBoneIndexByName = function (name) {
  71359. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  71360. if (this.bones[boneIndex].name === name) {
  71361. return boneIndex;
  71362. }
  71363. }
  71364. return -1;
  71365. };
  71366. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  71367. // check name not already in use
  71368. if (!this._ranges[name]) {
  71369. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  71370. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71371. if (this.bones[i].animations[0]) {
  71372. this.bones[i].animations[0].createRange(name, from, to);
  71373. }
  71374. }
  71375. }
  71376. };
  71377. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  71378. if (deleteFrames === void 0) { deleteFrames = true; }
  71379. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71380. if (this.bones[i].animations[0]) {
  71381. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  71382. }
  71383. }
  71384. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  71385. };
  71386. Skeleton.prototype.getAnimationRange = function (name) {
  71387. return this._ranges[name];
  71388. };
  71389. /**
  71390. * Returns as an Array, all AnimationRanges defined on this skeleton
  71391. */
  71392. Skeleton.prototype.getAnimationRanges = function () {
  71393. var animationRanges = [];
  71394. var name;
  71395. var i = 0;
  71396. for (name in this._ranges) {
  71397. animationRanges[i] = this._ranges[name];
  71398. i++;
  71399. }
  71400. return animationRanges;
  71401. };
  71402. /**
  71403. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  71404. */
  71405. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  71406. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71407. if (this._ranges[name] || !source.getAnimationRange(name)) {
  71408. return false;
  71409. }
  71410. var ret = true;
  71411. var frameOffset = this._getHighestAnimationFrame() + 1;
  71412. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  71413. var boneDict = {};
  71414. var sourceBones = source.bones;
  71415. var nBones;
  71416. var i;
  71417. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  71418. boneDict[sourceBones[i].name] = sourceBones[i];
  71419. }
  71420. if (this.bones.length !== sourceBones.length) {
  71421. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  71422. ret = false;
  71423. }
  71424. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  71425. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  71426. var boneName = this.bones[i].name;
  71427. var sourceBone = boneDict[boneName];
  71428. if (sourceBone) {
  71429. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  71430. }
  71431. else {
  71432. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  71433. ret = false;
  71434. }
  71435. }
  71436. // do not call createAnimationRange(), since it also is done to bones, which was already done
  71437. var range = source.getAnimationRange(name);
  71438. if (range) {
  71439. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  71440. }
  71441. return ret;
  71442. };
  71443. Skeleton.prototype.returnToRest = function () {
  71444. for (var index = 0; index < this.bones.length; index++) {
  71445. this.bones[index].returnToRest();
  71446. }
  71447. };
  71448. Skeleton.prototype._getHighestAnimationFrame = function () {
  71449. var ret = 0;
  71450. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71451. if (this.bones[i].animations[0]) {
  71452. var highest = this.bones[i].animations[0].getHighestFrame();
  71453. if (ret < highest) {
  71454. ret = highest;
  71455. }
  71456. }
  71457. }
  71458. return ret;
  71459. };
  71460. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  71461. var range = this.getAnimationRange(name);
  71462. if (!range) {
  71463. return null;
  71464. }
  71465. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  71466. };
  71467. Skeleton.prototype._markAsDirty = function () {
  71468. this._isDirty = true;
  71469. };
  71470. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  71471. this._meshesWithPoseMatrix.push(mesh);
  71472. };
  71473. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  71474. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  71475. if (index > -1) {
  71476. this._meshesWithPoseMatrix.splice(index, 1);
  71477. }
  71478. };
  71479. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  71480. this.onBeforeComputeObservable.notifyObservers(this);
  71481. for (var index = 0; index < this.bones.length; index++) {
  71482. var bone = this.bones[index];
  71483. var parentBone = bone.getParent();
  71484. if (parentBone) {
  71485. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  71486. }
  71487. else {
  71488. if (initialSkinMatrix) {
  71489. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  71490. }
  71491. else {
  71492. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  71493. }
  71494. }
  71495. if (bone._index !== -1) {
  71496. var mappedIndex = bone._index === null ? index : bone._index;
  71497. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  71498. }
  71499. }
  71500. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  71501. };
  71502. Skeleton.prototype.prepare = function () {
  71503. if (!this._isDirty) {
  71504. return;
  71505. }
  71506. if (this.needInitialSkinMatrix) {
  71507. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  71508. var mesh = this._meshesWithPoseMatrix[index];
  71509. var poseMatrix = mesh.getPoseMatrix();
  71510. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  71511. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71512. }
  71513. if (this._synchronizedWithMesh !== mesh) {
  71514. this._synchronizedWithMesh = mesh;
  71515. // Prepare bones
  71516. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  71517. var bone = this.bones[boneIndex];
  71518. if (!bone.getParent()) {
  71519. var matrix = bone.getBaseMatrix();
  71520. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  71521. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  71522. }
  71523. }
  71524. }
  71525. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  71526. }
  71527. }
  71528. else {
  71529. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  71530. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71531. }
  71532. this._computeTransformMatrices(this._transformMatrices, null);
  71533. }
  71534. this._isDirty = false;
  71535. this._scene._activeBones.addCount(this.bones.length, false);
  71536. };
  71537. Skeleton.prototype.getAnimatables = function () {
  71538. if (!this._animatables || this._animatables.length !== this.bones.length) {
  71539. this._animatables = [];
  71540. for (var index = 0; index < this.bones.length; index++) {
  71541. this._animatables.push(this.bones[index]);
  71542. }
  71543. }
  71544. return this._animatables;
  71545. };
  71546. Skeleton.prototype.clone = function (name, id) {
  71547. var result = new Skeleton(name, id || name, this._scene);
  71548. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71549. for (var index = 0; index < this.bones.length; index++) {
  71550. var source = this.bones[index];
  71551. var parentBone = null;
  71552. var parent_1 = source.getParent();
  71553. if (parent_1) {
  71554. var parentIndex = this.bones.indexOf(parent_1);
  71555. parentBone = result.bones[parentIndex];
  71556. }
  71557. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  71558. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  71559. }
  71560. if (this._ranges) {
  71561. result._ranges = {};
  71562. for (var rangeName in this._ranges) {
  71563. var range = this._ranges[rangeName];
  71564. if (range) {
  71565. result._ranges[rangeName] = range.clone();
  71566. }
  71567. }
  71568. }
  71569. this._isDirty = true;
  71570. return result;
  71571. };
  71572. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  71573. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  71574. this.bones.forEach(function (bone) {
  71575. bone.animations.forEach(function (animation) {
  71576. animation.enableBlending = true;
  71577. animation.blendingSpeed = blendingSpeed;
  71578. });
  71579. });
  71580. };
  71581. Skeleton.prototype.dispose = function () {
  71582. this._meshesWithPoseMatrix = [];
  71583. // Animations
  71584. this.getScene().stopAnimation(this);
  71585. // Remove from scene
  71586. this.getScene().removeSkeleton(this);
  71587. };
  71588. Skeleton.prototype.serialize = function () {
  71589. var serializationObject = {};
  71590. serializationObject.name = this.name;
  71591. serializationObject.id = this.id;
  71592. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  71593. serializationObject.bones = [];
  71594. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71595. for (var index = 0; index < this.bones.length; index++) {
  71596. var bone = this.bones[index];
  71597. var parent_2 = bone.getParent();
  71598. var serializedBone = {
  71599. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  71600. name: bone.name,
  71601. matrix: bone.getBaseMatrix().toArray(),
  71602. rest: bone.getRestPose().toArray()
  71603. };
  71604. serializationObject.bones.push(serializedBone);
  71605. if (bone.length) {
  71606. serializedBone.length = bone.length;
  71607. }
  71608. if (bone.animations && bone.animations.length > 0) {
  71609. serializedBone.animation = bone.animations[0].serialize();
  71610. }
  71611. serializationObject.ranges = [];
  71612. for (var name in this._ranges) {
  71613. var source = this._ranges[name];
  71614. if (!source) {
  71615. continue;
  71616. }
  71617. var range = {};
  71618. range.name = name;
  71619. range.from = source.from;
  71620. range.to = source.to;
  71621. serializationObject.ranges.push(range);
  71622. }
  71623. }
  71624. return serializationObject;
  71625. };
  71626. Skeleton.Parse = function (parsedSkeleton, scene) {
  71627. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  71628. if (parsedSkeleton.dimensionsAtRest) {
  71629. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  71630. }
  71631. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  71632. var index;
  71633. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  71634. var parsedBone = parsedSkeleton.bones[index];
  71635. var parentBone = null;
  71636. if (parsedBone.parentBoneIndex > -1) {
  71637. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  71638. }
  71639. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  71640. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  71641. if (parsedBone.length) {
  71642. bone.length = parsedBone.length;
  71643. }
  71644. if (parsedBone.animation) {
  71645. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  71646. }
  71647. }
  71648. // placed after bones, so createAnimationRange can cascade down
  71649. if (parsedSkeleton.ranges) {
  71650. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  71651. var data = parsedSkeleton.ranges[index];
  71652. skeleton.createAnimationRange(data.name, data.from, data.to);
  71653. }
  71654. }
  71655. return skeleton;
  71656. };
  71657. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  71658. if (forceUpdate === void 0) { forceUpdate = false; }
  71659. var renderId = this._scene.getRenderId();
  71660. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  71661. this.bones[0].computeAbsoluteTransforms();
  71662. this._lastAbsoluteTransformsUpdateId = renderId;
  71663. }
  71664. };
  71665. Skeleton.prototype.getPoseMatrix = function () {
  71666. var poseMatrix = null;
  71667. if (this._meshesWithPoseMatrix.length > 0) {
  71668. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  71669. }
  71670. return poseMatrix;
  71671. };
  71672. Skeleton.prototype.sortBones = function () {
  71673. var bones = new Array();
  71674. var visited = new Array(this.bones.length);
  71675. for (var index = 0; index < this.bones.length; index++) {
  71676. this._sortBones(index, bones, visited);
  71677. }
  71678. this.bones = bones;
  71679. };
  71680. Skeleton.prototype._sortBones = function (index, bones, visited) {
  71681. if (visited[index]) {
  71682. return;
  71683. }
  71684. visited[index] = true;
  71685. var bone = this.bones[index];
  71686. if (bone._index === undefined) {
  71687. bone._index = index;
  71688. }
  71689. var parentBone = bone.getParent();
  71690. if (parentBone) {
  71691. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  71692. }
  71693. bones.push(bone);
  71694. };
  71695. return Skeleton;
  71696. }());
  71697. BABYLON.Skeleton = Skeleton;
  71698. })(BABYLON || (BABYLON = {}));
  71699. //# sourceMappingURL=babylon.skeleton.js.map
  71700. var BABYLON;
  71701. (function (BABYLON) {
  71702. var SphericalPolynomial = /** @class */ (function () {
  71703. function SphericalPolynomial() {
  71704. this.x = BABYLON.Vector3.Zero();
  71705. this.y = BABYLON.Vector3.Zero();
  71706. this.z = BABYLON.Vector3.Zero();
  71707. this.xx = BABYLON.Vector3.Zero();
  71708. this.yy = BABYLON.Vector3.Zero();
  71709. this.zz = BABYLON.Vector3.Zero();
  71710. this.xy = BABYLON.Vector3.Zero();
  71711. this.yz = BABYLON.Vector3.Zero();
  71712. this.zx = BABYLON.Vector3.Zero();
  71713. }
  71714. SphericalPolynomial.prototype.addAmbient = function (color) {
  71715. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71716. this.xx = this.xx.add(colorVector);
  71717. this.yy = this.yy.add(colorVector);
  71718. this.zz = this.zz.add(colorVector);
  71719. };
  71720. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  71721. var result = new SphericalPolynomial();
  71722. result.x = harmonics.L11.scale(1.02333);
  71723. result.y = harmonics.L1_1.scale(1.02333);
  71724. result.z = harmonics.L10.scale(1.02333);
  71725. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  71726. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  71727. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  71728. result.yz = harmonics.L2_1.scale(0.858086);
  71729. result.zx = harmonics.L21.scale(0.858086);
  71730. result.xy = harmonics.L2_2.scale(0.858086);
  71731. result.scale(1.0 / Math.PI);
  71732. return result;
  71733. };
  71734. SphericalPolynomial.prototype.scale = function (scale) {
  71735. this.x = this.x.scale(scale);
  71736. this.y = this.y.scale(scale);
  71737. this.z = this.z.scale(scale);
  71738. this.xx = this.xx.scale(scale);
  71739. this.yy = this.yy.scale(scale);
  71740. this.zz = this.zz.scale(scale);
  71741. this.yz = this.yz.scale(scale);
  71742. this.zx = this.zx.scale(scale);
  71743. this.xy = this.xy.scale(scale);
  71744. };
  71745. return SphericalPolynomial;
  71746. }());
  71747. BABYLON.SphericalPolynomial = SphericalPolynomial;
  71748. var SphericalHarmonics = /** @class */ (function () {
  71749. function SphericalHarmonics() {
  71750. this.L00 = BABYLON.Vector3.Zero();
  71751. this.L1_1 = BABYLON.Vector3.Zero();
  71752. this.L10 = BABYLON.Vector3.Zero();
  71753. this.L11 = BABYLON.Vector3.Zero();
  71754. this.L2_2 = BABYLON.Vector3.Zero();
  71755. this.L2_1 = BABYLON.Vector3.Zero();
  71756. this.L20 = BABYLON.Vector3.Zero();
  71757. this.L21 = BABYLON.Vector3.Zero();
  71758. this.L22 = BABYLON.Vector3.Zero();
  71759. }
  71760. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  71761. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71762. var c = colorVector.scale(deltaSolidAngle);
  71763. this.L00 = this.L00.add(c.scale(0.282095));
  71764. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  71765. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  71766. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  71767. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  71768. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  71769. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  71770. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  71771. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  71772. };
  71773. SphericalHarmonics.prototype.scale = function (scale) {
  71774. this.L00 = this.L00.scale(scale);
  71775. this.L1_1 = this.L1_1.scale(scale);
  71776. this.L10 = this.L10.scale(scale);
  71777. this.L11 = this.L11.scale(scale);
  71778. this.L2_2 = this.L2_2.scale(scale);
  71779. this.L2_1 = this.L2_1.scale(scale);
  71780. this.L20 = this.L20.scale(scale);
  71781. this.L21 = this.L21.scale(scale);
  71782. this.L22 = this.L22.scale(scale);
  71783. };
  71784. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  71785. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  71786. //
  71787. // E_lm = A_l * L_lm
  71788. //
  71789. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  71790. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  71791. // the scaling factors are given in equation 9.
  71792. // Constant (Band 0)
  71793. this.L00 = this.L00.scale(3.141593);
  71794. // Linear (Band 1)
  71795. this.L1_1 = this.L1_1.scale(2.094395);
  71796. this.L10 = this.L10.scale(2.094395);
  71797. this.L11 = this.L11.scale(2.094395);
  71798. // Quadratic (Band 2)
  71799. this.L2_2 = this.L2_2.scale(0.785398);
  71800. this.L2_1 = this.L2_1.scale(0.785398);
  71801. this.L20 = this.L20.scale(0.785398);
  71802. this.L21 = this.L21.scale(0.785398);
  71803. this.L22 = this.L22.scale(0.785398);
  71804. };
  71805. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  71806. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  71807. // L = (1/pi) * E * rho
  71808. //
  71809. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  71810. this.scale(1.0 / Math.PI);
  71811. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  71812. // (The pixel shader must apply albedo after texture fetches, etc).
  71813. };
  71814. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  71815. var result = new SphericalHarmonics();
  71816. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  71817. result.L1_1 = polynomial.y.scale(0.977204);
  71818. result.L10 = polynomial.z.scale(0.977204);
  71819. result.L11 = polynomial.x.scale(0.977204);
  71820. result.L2_2 = polynomial.xy.scale(1.16538);
  71821. result.L2_1 = polynomial.yz.scale(1.16538);
  71822. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  71823. result.L21 = polynomial.zx.scale(1.16538);
  71824. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  71825. result.scale(Math.PI);
  71826. return result;
  71827. };
  71828. return SphericalHarmonics;
  71829. }());
  71830. BABYLON.SphericalHarmonics = SphericalHarmonics;
  71831. })(BABYLON || (BABYLON = {}));
  71832. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  71833. var BABYLON;
  71834. (function (BABYLON) {
  71835. var FileFaceOrientation = /** @class */ (function () {
  71836. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  71837. this.name = name;
  71838. this.worldAxisForNormal = worldAxisForNormal;
  71839. this.worldAxisForFileX = worldAxisForFileX;
  71840. this.worldAxisForFileY = worldAxisForFileY;
  71841. }
  71842. return FileFaceOrientation;
  71843. }());
  71844. ;
  71845. /**
  71846. * Helper class dealing with the extraction of spherical polynomial dataArray
  71847. * from a cube map.
  71848. */
  71849. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  71850. function CubeMapToSphericalPolynomialTools() {
  71851. }
  71852. /**
  71853. * Converts a texture to the according Spherical Polynomial data.
  71854. * This extracts the first 3 orders only as they are the only one used in the lighting.
  71855. *
  71856. * @param texture The texture to extract the information from.
  71857. * @return The Spherical Polynomial data.
  71858. */
  71859. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  71860. if (!texture.isCube) {
  71861. // Only supports cube Textures currently.
  71862. return null;
  71863. }
  71864. var size = texture.getSize().width;
  71865. var right = texture.readPixels(0);
  71866. var left = texture.readPixels(1);
  71867. var up;
  71868. var down;
  71869. if (texture.isRenderTarget) {
  71870. up = texture.readPixels(3);
  71871. down = texture.readPixels(2);
  71872. }
  71873. else {
  71874. up = texture.readPixels(2);
  71875. down = texture.readPixels(3);
  71876. }
  71877. var front = texture.readPixels(4);
  71878. var back = texture.readPixels(5);
  71879. var gammaSpace = texture.gammaSpace;
  71880. // Always read as RGBA.
  71881. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  71882. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  71883. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71884. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71885. }
  71886. var cubeInfo = {
  71887. size: size,
  71888. right: right,
  71889. left: left,
  71890. up: up,
  71891. down: down,
  71892. front: front,
  71893. back: back,
  71894. format: format,
  71895. type: type,
  71896. gammaSpace: gammaSpace,
  71897. };
  71898. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  71899. };
  71900. /**
  71901. * Converts a cubemap to the according Spherical Polynomial data.
  71902. * This extracts the first 3 orders only as they are the only one used in the lighting.
  71903. *
  71904. * @param cubeInfo The Cube map to extract the information from.
  71905. * @return The Spherical Polynomial data.
  71906. */
  71907. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  71908. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  71909. var totalSolidAngle = 0.0;
  71910. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  71911. var du = 2.0 / cubeInfo.size;
  71912. var dv = du;
  71913. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  71914. var minUV = du * 0.5 - 1.0;
  71915. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71916. var fileFace = this.FileFaces[faceIndex];
  71917. var dataArray = cubeInfo[fileFace.name];
  71918. var v = minUV;
  71919. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  71920. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  71921. // Because SP is still linear, so summation is fine in that basis.
  71922. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  71923. for (var y = 0; y < cubeInfo.size; y++) {
  71924. var u = minUV;
  71925. for (var x = 0; x < cubeInfo.size; x++) {
  71926. // World direction (not normalised)
  71927. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  71928. worldDirection.normalize();
  71929. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  71930. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  71931. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  71932. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  71933. // Handle Integer types.
  71934. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71935. r /= 255;
  71936. g /= 255;
  71937. b /= 255;
  71938. }
  71939. // Handle Gamma space textures.
  71940. if (cubeInfo.gammaSpace) {
  71941. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  71942. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  71943. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  71944. }
  71945. var color = new BABYLON.Color3(r, g, b);
  71946. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  71947. totalSolidAngle += deltaSolidAngle;
  71948. u += du;
  71949. }
  71950. v += dv;
  71951. }
  71952. }
  71953. // Solid angle for entire sphere is 4*pi
  71954. var sphereSolidAngle = 4.0 * Math.PI;
  71955. // Adjust the solid angle to allow for how many faces we processed.
  71956. var facesProcessed = 6.0;
  71957. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  71958. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  71959. // This is needed because the numerical integration over the cube uses a
  71960. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  71961. // and also to compensate for accumulative error due to float precision in the summation.
  71962. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  71963. sphericalHarmonics.scale(correctionFactor);
  71964. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  71965. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  71966. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  71967. };
  71968. CubeMapToSphericalPolynomialTools.FileFaces = [
  71969. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  71970. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  71971. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  71972. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  71973. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  71974. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  71975. ];
  71976. return CubeMapToSphericalPolynomialTools;
  71977. }());
  71978. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  71979. })(BABYLON || (BABYLON = {}));
  71980. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  71981. var BABYLON;
  71982. (function (BABYLON) {
  71983. /**
  71984. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  71985. */
  71986. var PanoramaToCubeMapTools = /** @class */ (function () {
  71987. function PanoramaToCubeMapTools() {
  71988. }
  71989. /**
  71990. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  71991. *
  71992. * @param float32Array The source data.
  71993. * @param inputWidth The width of the input panorama.
  71994. * @param inputhHeight The height of the input panorama.
  71995. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  71996. * @return The cubemap data
  71997. */
  71998. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  71999. if (!float32Array) {
  72000. throw "ConvertPanoramaToCubemap: input cannot be null";
  72001. }
  72002. if (float32Array.length != inputWidth * inputHeight * 3) {
  72003. throw "ConvertPanoramaToCubemap: input size is wrong";
  72004. }
  72005. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  72006. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  72007. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  72008. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  72009. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  72010. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  72011. return {
  72012. front: textureFront,
  72013. back: textureBack,
  72014. left: textureLeft,
  72015. right: textureRight,
  72016. up: textureUp,
  72017. down: textureDown,
  72018. size: size,
  72019. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  72020. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  72021. gammaSpace: false,
  72022. };
  72023. };
  72024. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  72025. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  72026. var textureArray = new Float32Array(buffer);
  72027. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  72028. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  72029. var dy = 1 / texSize;
  72030. var fy = 0;
  72031. for (var y = 0; y < texSize; y++) {
  72032. var xv1 = faceData[0];
  72033. var xv2 = faceData[2];
  72034. for (var x = 0; x < texSize; x++) {
  72035. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  72036. v.normalize();
  72037. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  72038. // 3 channels per pixels
  72039. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  72040. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  72041. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  72042. xv1 = xv1.add(rotDX1);
  72043. xv2 = xv2.add(rotDX2);
  72044. }
  72045. fy += dy;
  72046. }
  72047. return textureArray;
  72048. };
  72049. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  72050. var theta = Math.atan2(vDir.z, vDir.x);
  72051. var phi = Math.acos(vDir.y);
  72052. while (theta < -Math.PI)
  72053. theta += 2 * Math.PI;
  72054. while (theta > Math.PI)
  72055. theta -= 2 * Math.PI;
  72056. var dx = theta / Math.PI;
  72057. var dy = phi / Math.PI;
  72058. // recenter.
  72059. dx = dx * 0.5 + 0.5;
  72060. var px = Math.round(dx * inputWidth);
  72061. if (px < 0)
  72062. px = 0;
  72063. else if (px >= inputWidth)
  72064. px = inputWidth - 1;
  72065. var py = Math.round(dy * inputHeight);
  72066. if (py < 0)
  72067. py = 0;
  72068. else if (py >= inputHeight)
  72069. py = inputHeight - 1;
  72070. var inputY = (inputHeight - py - 1);
  72071. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  72072. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  72073. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  72074. return {
  72075. r: r,
  72076. g: g,
  72077. b: b
  72078. };
  72079. };
  72080. PanoramaToCubeMapTools.FACE_FRONT = [
  72081. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72082. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72083. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72084. new BABYLON.Vector3(1.0, 1.0, -1.0)
  72085. ];
  72086. PanoramaToCubeMapTools.FACE_BACK = [
  72087. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72088. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72089. new BABYLON.Vector3(1.0, 1.0, 1.0),
  72090. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  72091. ];
  72092. PanoramaToCubeMapTools.FACE_RIGHT = [
  72093. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72094. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72095. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72096. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72097. ];
  72098. PanoramaToCubeMapTools.FACE_LEFT = [
  72099. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72100. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72101. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72102. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  72103. ];
  72104. PanoramaToCubeMapTools.FACE_DOWN = [
  72105. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72106. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72107. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72108. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72109. ];
  72110. PanoramaToCubeMapTools.FACE_UP = [
  72111. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72112. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72113. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72114. new BABYLON.Vector3(1.0, -1.0, -1.0)
  72115. ];
  72116. return PanoramaToCubeMapTools;
  72117. }());
  72118. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  72119. })(BABYLON || (BABYLON = {}));
  72120. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  72121. var BABYLON;
  72122. (function (BABYLON) {
  72123. ;
  72124. /**
  72125. * This groups tools to convert HDR texture to native colors array.
  72126. */
  72127. var HDRTools = /** @class */ (function () {
  72128. function HDRTools() {
  72129. }
  72130. HDRTools.Ldexp = function (mantissa, exponent) {
  72131. if (exponent > 1023) {
  72132. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  72133. }
  72134. if (exponent < -1074) {
  72135. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  72136. }
  72137. return mantissa * Math.pow(2, exponent);
  72138. };
  72139. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  72140. if (exponent > 0) {
  72141. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  72142. float32array[index + 0] = red * exponent;
  72143. float32array[index + 1] = green * exponent;
  72144. float32array[index + 2] = blue * exponent;
  72145. }
  72146. else {
  72147. float32array[index + 0] = 0;
  72148. float32array[index + 1] = 0;
  72149. float32array[index + 2] = 0;
  72150. }
  72151. };
  72152. HDRTools.readStringLine = function (uint8array, startIndex) {
  72153. var line = "";
  72154. var character = "";
  72155. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  72156. character = String.fromCharCode(uint8array[i]);
  72157. if (character == "\n") {
  72158. break;
  72159. }
  72160. line += character;
  72161. }
  72162. return line;
  72163. };
  72164. /**
  72165. * Reads header information from an RGBE texture stored in a native array.
  72166. * More information on this format are available here:
  72167. * https://en.wikipedia.org/wiki/RGBE_image_format
  72168. *
  72169. * @param uint8array The binary file stored in native array.
  72170. * @return The header information.
  72171. */
  72172. HDRTools.RGBE_ReadHeader = function (uint8array) {
  72173. var height = 0;
  72174. var width = 0;
  72175. var line = this.readStringLine(uint8array, 0);
  72176. if (line[0] != '#' || line[1] != '?') {
  72177. throw "Bad HDR Format.";
  72178. }
  72179. var endOfHeader = false;
  72180. var findFormat = false;
  72181. var lineIndex = 0;
  72182. do {
  72183. lineIndex += (line.length + 1);
  72184. line = this.readStringLine(uint8array, lineIndex);
  72185. if (line == "FORMAT=32-bit_rle_rgbe") {
  72186. findFormat = true;
  72187. }
  72188. else if (line.length == 0) {
  72189. endOfHeader = true;
  72190. }
  72191. } while (!endOfHeader);
  72192. if (!findFormat) {
  72193. throw "HDR Bad header format, unsupported FORMAT";
  72194. }
  72195. lineIndex += (line.length + 1);
  72196. line = this.readStringLine(uint8array, lineIndex);
  72197. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  72198. var match = sizeRegexp.exec(line);
  72199. // TODO. Support +Y and -X if needed.
  72200. if (!match || match.length < 3) {
  72201. throw "HDR Bad header format, no size";
  72202. }
  72203. width = parseInt(match[2]);
  72204. height = parseInt(match[1]);
  72205. if (width < 8 || width > 0x7fff) {
  72206. throw "HDR Bad header format, unsupported size";
  72207. }
  72208. lineIndex += (line.length + 1);
  72209. return {
  72210. height: height,
  72211. width: width,
  72212. dataPosition: lineIndex
  72213. };
  72214. };
  72215. /**
  72216. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  72217. * This RGBE texture needs to store the information as a panorama.
  72218. *
  72219. * More information on this format are available here:
  72220. * https://en.wikipedia.org/wiki/RGBE_image_format
  72221. *
  72222. * @param buffer The binary file stored in an array buffer.
  72223. * @param size The expected size of the extracted cubemap.
  72224. * @return The Cube Map information.
  72225. */
  72226. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  72227. var uint8array = new Uint8Array(buffer);
  72228. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  72229. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72230. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  72231. return cubeMapData;
  72232. };
  72233. /**
  72234. * Returns the pixels data extracted from an RGBE texture.
  72235. * This pixels will be stored left to right up to down in the R G B order in one array.
  72236. *
  72237. * More information on this format are available here:
  72238. * https://en.wikipedia.org/wiki/RGBE_image_format
  72239. *
  72240. * @param uint8array The binary file stored in an array buffer.
  72241. * @param hdrInfo The header information of the file.
  72242. * @return The pixels data in RGB right to left up to down order.
  72243. */
  72244. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  72245. // Keep for multi format supports.
  72246. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72247. };
  72248. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  72249. var num_scanlines = hdrInfo.height;
  72250. var scanline_width = hdrInfo.width;
  72251. var a, b, c, d, count;
  72252. var dataIndex = hdrInfo.dataPosition;
  72253. var index = 0, endIndex = 0, i = 0;
  72254. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  72255. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  72256. // 3 channels of 4 bytes per pixel in float.
  72257. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  72258. var resultArray = new Float32Array(resultBuffer);
  72259. // read in each successive scanline
  72260. while (num_scanlines > 0) {
  72261. a = uint8array[dataIndex++];
  72262. b = uint8array[dataIndex++];
  72263. c = uint8array[dataIndex++];
  72264. d = uint8array[dataIndex++];
  72265. if (a != 2 || b != 2 || (c & 0x80)) {
  72266. // this file is not run length encoded
  72267. throw "HDR Bad header format, not RLE";
  72268. }
  72269. if (((c << 8) | d) != scanline_width) {
  72270. throw "HDR Bad header format, wrong scan line width";
  72271. }
  72272. index = 0;
  72273. // read each of the four channels for the scanline into the buffer
  72274. for (i = 0; i < 4; i++) {
  72275. endIndex = (i + 1) * scanline_width;
  72276. while (index < endIndex) {
  72277. a = uint8array[dataIndex++];
  72278. b = uint8array[dataIndex++];
  72279. if (a > 128) {
  72280. // a run of the same value
  72281. count = a - 128;
  72282. if ((count == 0) || (count > endIndex - index)) {
  72283. throw "HDR Bad Format, bad scanline data (run)";
  72284. }
  72285. while (count-- > 0) {
  72286. scanLineArray[index++] = b;
  72287. }
  72288. }
  72289. else {
  72290. // a non-run
  72291. count = a;
  72292. if ((count == 0) || (count > endIndex - index)) {
  72293. throw "HDR Bad Format, bad scanline data (non-run)";
  72294. }
  72295. scanLineArray[index++] = b;
  72296. if (--count > 0) {
  72297. for (var j = 0; j < count; j++) {
  72298. scanLineArray[index++] = uint8array[dataIndex++];
  72299. }
  72300. }
  72301. }
  72302. }
  72303. }
  72304. // now convert data from buffer into floats
  72305. for (i = 0; i < scanline_width; i++) {
  72306. a = scanLineArray[i];
  72307. b = scanLineArray[i + scanline_width];
  72308. c = scanLineArray[i + 2 * scanline_width];
  72309. d = scanLineArray[i + 3 * scanline_width];
  72310. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  72311. }
  72312. num_scanlines--;
  72313. }
  72314. return resultArray;
  72315. };
  72316. return HDRTools;
  72317. }());
  72318. BABYLON.HDRTools = HDRTools;
  72319. })(BABYLON || (BABYLON = {}));
  72320. //# sourceMappingURL=babylon.hdr.js.map
  72321. var BABYLON;
  72322. (function (BABYLON) {
  72323. /**
  72324. * This represents a texture coming from an HDR input.
  72325. *
  72326. * The only supported format is currently panorama picture stored in RGBE format.
  72327. * Example of such files can be found on HDRLib: http://hdrlib.com/
  72328. */
  72329. var HDRCubeTexture = /** @class */ (function (_super) {
  72330. __extends(HDRCubeTexture, _super);
  72331. /**
  72332. * Instantiates an HDRTexture from the following parameters.
  72333. *
  72334. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  72335. * @param scene The scene the texture will be used in
  72336. * @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.
  72337. * @param noMipmap Forces to not generate the mipmap if true
  72338. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  72339. * @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)
  72340. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  72341. */
  72342. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  72343. if (noMipmap === void 0) { noMipmap = false; }
  72344. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72345. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72346. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72347. if (onLoad === void 0) { onLoad = null; }
  72348. if (onError === void 0) { onError = null; }
  72349. var _this = _super.call(this, scene) || this;
  72350. _this._useInGammaSpace = false;
  72351. _this._generateHarmonics = true;
  72352. _this._isBABYLONPreprocessed = false;
  72353. _this._onLoad = null;
  72354. _this._onError = null;
  72355. /**
  72356. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  72357. */
  72358. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72359. /**
  72360. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  72361. * This is usefull at run time to apply the good shader.
  72362. */
  72363. _this.isPMREM = false;
  72364. _this._isBlocking = true;
  72365. if (!url) {
  72366. return _this;
  72367. }
  72368. _this.name = url;
  72369. _this.url = url;
  72370. _this.hasAlpha = false;
  72371. _this.isCube = true;
  72372. _this._textureMatrix = BABYLON.Matrix.Identity();
  72373. _this._onLoad = onLoad;
  72374. _this._onError = onError;
  72375. _this.gammaSpace = false;
  72376. var caps = scene.getEngine().getCaps();
  72377. if (size) {
  72378. _this._isBABYLONPreprocessed = false;
  72379. _this._noMipmap = noMipmap;
  72380. _this._size = size;
  72381. _this._useInGammaSpace = useInGammaSpace;
  72382. _this._usePMREMGenerator = usePMREMGenerator &&
  72383. caps.textureLOD &&
  72384. caps.textureFloat &&
  72385. !_this._useInGammaSpace;
  72386. }
  72387. else {
  72388. _this._isBABYLONPreprocessed = true;
  72389. _this._noMipmap = false;
  72390. _this._useInGammaSpace = false;
  72391. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  72392. !_this._useInGammaSpace;
  72393. }
  72394. _this.isPMREM = _this._usePMREMGenerator;
  72395. _this._texture = _this._getFromCache(url, _this._noMipmap);
  72396. if (!_this._texture) {
  72397. if (!scene.useDelayedTextureLoading) {
  72398. _this.loadTexture();
  72399. }
  72400. else {
  72401. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72402. }
  72403. }
  72404. return _this;
  72405. }
  72406. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  72407. /**
  72408. * Gets wether or not the texture is blocking during loading.
  72409. */
  72410. get: function () {
  72411. return this._isBlocking;
  72412. },
  72413. /**
  72414. * Sets wether or not the texture is blocking during loading.
  72415. */
  72416. set: function (value) {
  72417. this._isBlocking = value;
  72418. },
  72419. enumerable: true,
  72420. configurable: true
  72421. });
  72422. /**
  72423. * Occurs when the file is a preprocessed .babylon.hdr file.
  72424. */
  72425. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  72426. var _this = this;
  72427. var mipLevels = 0;
  72428. var floatArrayView = null;
  72429. var scene = this.getScene();
  72430. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  72431. var mips = new Array();
  72432. if (!floatArrayView) {
  72433. return mips;
  72434. }
  72435. var startIndex = 30;
  72436. for (var level = 0; level < mipLevels; level++) {
  72437. mips.push([]);
  72438. // Fill each pixel of the mip level.
  72439. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  72440. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72441. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  72442. mips[level].push(faceData);
  72443. startIndex += faceSize;
  72444. }
  72445. }
  72446. return mips;
  72447. } : null;
  72448. var callback = function (buffer) {
  72449. var scene = _this.getScene();
  72450. if (!scene) {
  72451. return null;
  72452. }
  72453. // Create Native Array Views
  72454. var intArrayView = new Int32Array(buffer);
  72455. floatArrayView = new Float32Array(buffer);
  72456. // Fill header.
  72457. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  72458. _this._size = intArrayView[1]; // CubeMap max mip face size.
  72459. // Update Texture Information.
  72460. if (!_this._texture) {
  72461. return null;
  72462. }
  72463. _this._texture.updateSize(_this._size, _this._size);
  72464. // Fill polynomial information.
  72465. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  72466. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  72467. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  72468. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  72469. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  72470. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  72471. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  72472. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  72473. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  72474. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  72475. _this.sphericalPolynomial = sphericalPolynomial;
  72476. // Fill pixel data.
  72477. mipLevels = intArrayView[29]; // Number of mip levels.
  72478. var startIndex = 30;
  72479. var data = [];
  72480. var faceSize = Math.pow(_this._size, 2) * 3;
  72481. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72482. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  72483. startIndex += faceSize;
  72484. }
  72485. var results = [];
  72486. var byteArray = null;
  72487. // Push each faces.
  72488. for (var k = 0; k < 6; k++) {
  72489. var dataFace = null;
  72490. // To be deprecated.
  72491. if (version === 1) {
  72492. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  72493. dataFace = data[j];
  72494. }
  72495. // If special cases.
  72496. if (!mipmapGenerator && dataFace) {
  72497. if (!scene.getEngine().getCaps().textureFloat) {
  72498. // 3 channels of 1 bytes per pixel in bytes.
  72499. var byteBuffer = new ArrayBuffer(faceSize);
  72500. byteArray = new Uint8Array(byteBuffer);
  72501. }
  72502. for (var i = 0; i < _this._size * _this._size; i++) {
  72503. // Put in gamma space if requested.
  72504. if (_this._useInGammaSpace) {
  72505. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72506. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72507. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72508. }
  72509. // Convert to int texture for fallback.
  72510. if (byteArray) {
  72511. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72512. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72513. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72514. // May use luminance instead if the result is not accurate.
  72515. var max = Math.max(Math.max(r, g), b);
  72516. if (max > 255) {
  72517. var scale = 255 / max;
  72518. r *= scale;
  72519. g *= scale;
  72520. b *= scale;
  72521. }
  72522. byteArray[(i * 3) + 0] = r;
  72523. byteArray[(i * 3) + 1] = g;
  72524. byteArray[(i * 3) + 2] = b;
  72525. }
  72526. }
  72527. }
  72528. // Fill the array accordingly.
  72529. if (byteArray) {
  72530. results.push(byteArray);
  72531. }
  72532. else {
  72533. results.push(dataFace);
  72534. }
  72535. }
  72536. return results;
  72537. };
  72538. if (scene) {
  72539. 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);
  72540. }
  72541. };
  72542. /**
  72543. * Occurs when the file is raw .hdr file.
  72544. */
  72545. HDRCubeTexture.prototype.loadHDRTexture = function () {
  72546. var _this = this;
  72547. var callback = function (buffer) {
  72548. var scene = _this.getScene();
  72549. if (!scene) {
  72550. return null;
  72551. }
  72552. // Extract the raw linear data.
  72553. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  72554. // Generate harmonics if needed.
  72555. if (_this._generateHarmonics) {
  72556. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  72557. _this.sphericalPolynomial = sphericalPolynomial;
  72558. }
  72559. var results = [];
  72560. var byteArray = null;
  72561. // Push each faces.
  72562. for (var j = 0; j < 6; j++) {
  72563. // Create uintarray fallback.
  72564. if (!scene.getEngine().getCaps().textureFloat) {
  72565. // 3 channels of 1 bytes per pixel in bytes.
  72566. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  72567. byteArray = new Uint8Array(byteBuffer);
  72568. }
  72569. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  72570. // If special cases.
  72571. if (_this._useInGammaSpace || byteArray) {
  72572. for (var i = 0; i < _this._size * _this._size; i++) {
  72573. // Put in gamma space if requested.
  72574. if (_this._useInGammaSpace) {
  72575. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72576. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72577. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72578. }
  72579. // Convert to int texture for fallback.
  72580. if (byteArray) {
  72581. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72582. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72583. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72584. // May use luminance instead if the result is not accurate.
  72585. var max = Math.max(Math.max(r, g), b);
  72586. if (max > 255) {
  72587. var scale = 255 / max;
  72588. r *= scale;
  72589. g *= scale;
  72590. b *= scale;
  72591. }
  72592. byteArray[(i * 3) + 0] = r;
  72593. byteArray[(i * 3) + 1] = g;
  72594. byteArray[(i * 3) + 2] = b;
  72595. }
  72596. }
  72597. }
  72598. if (byteArray) {
  72599. results.push(byteArray);
  72600. }
  72601. else {
  72602. results.push(dataFace);
  72603. }
  72604. }
  72605. return results;
  72606. };
  72607. var mipmapGenerator = null;
  72608. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  72609. // if (!this._noMipmap &&
  72610. // this._usePMREMGenerator) {
  72611. // mipmapGenerator = (data: ArrayBufferView[]) => {
  72612. // // Custom setup of the generator matching with the PBR shader values.
  72613. // var generator = new BABYLON.PMREMGenerator(data,
  72614. // this._size,
  72615. // this._size,
  72616. // 0,
  72617. // 3,
  72618. // this.getScene().getEngine().getCaps().textureFloat,
  72619. // 2048,
  72620. // 0.25,
  72621. // false,
  72622. // true);
  72623. // return generator.filterCubeMap();
  72624. // };
  72625. // }
  72626. var scene = this.getScene();
  72627. if (scene) {
  72628. 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);
  72629. }
  72630. };
  72631. /**
  72632. * Starts the loading process of the texture.
  72633. */
  72634. HDRCubeTexture.prototype.loadTexture = function () {
  72635. if (this._isBABYLONPreprocessed) {
  72636. this.loadBabylonTexture();
  72637. }
  72638. else {
  72639. this.loadHDRTexture();
  72640. }
  72641. };
  72642. HDRCubeTexture.prototype.clone = function () {
  72643. var scene = this.getScene();
  72644. if (!scene) {
  72645. return this;
  72646. }
  72647. var size = (this._isBABYLONPreprocessed ? null : this._size);
  72648. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  72649. // Base texture
  72650. newTexture.level = this.level;
  72651. newTexture.wrapU = this.wrapU;
  72652. newTexture.wrapV = this.wrapV;
  72653. newTexture.coordinatesIndex = this.coordinatesIndex;
  72654. newTexture.coordinatesMode = this.coordinatesMode;
  72655. return newTexture;
  72656. };
  72657. // Methods
  72658. HDRCubeTexture.prototype.delayLoad = function () {
  72659. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  72660. return;
  72661. }
  72662. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  72663. this._texture = this._getFromCache(this.url, this._noMipmap);
  72664. if (!this._texture) {
  72665. this.loadTexture();
  72666. }
  72667. };
  72668. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  72669. return this._textureMatrix;
  72670. };
  72671. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  72672. this._textureMatrix = value;
  72673. };
  72674. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  72675. var texture = null;
  72676. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  72677. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  72678. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  72679. texture.name = parsedTexture.name;
  72680. texture.hasAlpha = parsedTexture.hasAlpha;
  72681. texture.level = parsedTexture.level;
  72682. texture.coordinatesMode = parsedTexture.coordinatesMode;
  72683. texture.isBlocking = parsedTexture.isBlocking;
  72684. }
  72685. return texture;
  72686. };
  72687. HDRCubeTexture.prototype.serialize = function () {
  72688. if (!this.name) {
  72689. return null;
  72690. }
  72691. var serializationObject = {};
  72692. serializationObject.name = this.name;
  72693. serializationObject.hasAlpha = this.hasAlpha;
  72694. serializationObject.isCube = true;
  72695. serializationObject.level = this.level;
  72696. serializationObject.size = this._size;
  72697. serializationObject.coordinatesMode = this.coordinatesMode;
  72698. serializationObject.useInGammaSpace = this._useInGammaSpace;
  72699. serializationObject.generateHarmonics = this._generateHarmonics;
  72700. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  72701. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  72702. serializationObject.customType = "BABYLON.HDRCubeTexture";
  72703. serializationObject.noMipmap = this._noMipmap;
  72704. serializationObject.isBlocking = this._isBlocking;
  72705. return serializationObject;
  72706. };
  72707. /**
  72708. * Saves as a file the data contained in the texture in a binary format.
  72709. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72710. * as the spherical used in the lighting.
  72711. * @param url The HDR file url.
  72712. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72713. * @param onError Method called if any error happens during download.
  72714. * @return The packed binary data.
  72715. */
  72716. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  72717. if (onError === void 0) { onError = null; }
  72718. var callback = function (buffer) {
  72719. var data = new Blob([buffer], { type: 'application/octet-stream' });
  72720. // Returns a URL you can use as a href.
  72721. var objUrl = window.URL.createObjectURL(data);
  72722. // Simulates a link to it and click to dowload.
  72723. var a = document.createElement("a");
  72724. document.body.appendChild(a);
  72725. a.style.display = "none";
  72726. a.href = objUrl;
  72727. a.download = "envmap.babylon.hdr";
  72728. a.click();
  72729. };
  72730. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  72731. };
  72732. /**
  72733. * Serializes the data contained in the texture in a binary format.
  72734. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72735. * as the spherical used in the lighting.
  72736. * @param url The HDR file url.
  72737. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72738. * @param onError Method called if any error happens during download.
  72739. * @return The packed binary data.
  72740. */
  72741. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  72742. if (onError === void 0) { onError = null; }
  72743. // Needs the url tho create the texture.
  72744. if (!url) {
  72745. return;
  72746. }
  72747. // Check Power of two size.
  72748. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  72749. return;
  72750. }
  72751. // Coming Back in 3.x.
  72752. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  72753. };
  72754. HDRCubeTexture._facesMapping = [
  72755. "right",
  72756. "left",
  72757. "up",
  72758. "down",
  72759. "front",
  72760. "back"
  72761. ];
  72762. return HDRCubeTexture;
  72763. }(BABYLON.BaseTexture));
  72764. BABYLON.HDRCubeTexture = HDRCubeTexture;
  72765. })(BABYLON || (BABYLON = {}));
  72766. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  72767. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  72768. // Huge respect for a such great lib.
  72769. // Earcut license:
  72770. // Copyright (c) 2016, Mapbox
  72771. //
  72772. // Permission to use, copy, modify, and/or distribute this software for any purpose
  72773. // with or without fee is hereby granted, provided that the above copyright notice
  72774. // and this permission notice appear in all copies.
  72775. //
  72776. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  72777. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  72778. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  72779. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  72780. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  72781. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  72782. // THIS SOFTWARE.
  72783. var Earcut;
  72784. (function (Earcut) {
  72785. /**
  72786. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  72787. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  72788. * @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).
  72789. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  72790. */
  72791. function earcut(data, holeIndices, dim) {
  72792. dim = dim || 2;
  72793. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  72794. if (!outerNode)
  72795. return triangles;
  72796. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  72797. if (hasHoles)
  72798. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  72799. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  72800. if (data.length > 80 * dim) {
  72801. minX = maxX = data[0];
  72802. minY = maxY = data[1];
  72803. for (var i = dim; i < outerLen; i += dim) {
  72804. x = data[i];
  72805. y = data[i + 1];
  72806. if (x < minX)
  72807. minX = x;
  72808. if (y < minY)
  72809. minY = y;
  72810. if (x > maxX)
  72811. maxX = x;
  72812. if (y > maxY)
  72813. maxY = y;
  72814. }
  72815. // minX, minY and size are later used to transform coords into integers for z-order calculation
  72816. size = Math.max(maxX - minX, maxY - minY);
  72817. }
  72818. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  72819. return triangles;
  72820. }
  72821. Earcut.earcut = earcut;
  72822. var Node = /** @class */ (function () {
  72823. function Node(i, x, y) {
  72824. this.i = i;
  72825. this.x = x;
  72826. this.y = y;
  72827. this.prev = null;
  72828. this.next = null;
  72829. this.z = null;
  72830. this.prevZ = null;
  72831. this.nextZ = null;
  72832. this.steiner = false;
  72833. }
  72834. return Node;
  72835. }());
  72836. // create a circular doubly linked list from polygon points in the specified winding order
  72837. function linkedList(data, start, end, dim, clockwise) {
  72838. var i, last = null;
  72839. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  72840. for (i = start; i < end; i += dim)
  72841. last = insertNode(i, data[i], data[i + 1], last);
  72842. }
  72843. else {
  72844. for (i = end - dim; i >= start; i -= dim)
  72845. last = insertNode(i, data[i], data[i + 1], last);
  72846. }
  72847. if (last && equals(last, last.next)) {
  72848. removeNode(last);
  72849. last = last.next;
  72850. }
  72851. return last;
  72852. }
  72853. // eliminate colinear or duplicate points
  72854. function filterPoints(start, end) {
  72855. if (!start)
  72856. return start;
  72857. if (!end)
  72858. end = start;
  72859. var p = start, again;
  72860. do {
  72861. again = false;
  72862. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  72863. removeNode(p);
  72864. p = end = p.prev;
  72865. if (p === p.next)
  72866. return undefined;
  72867. again = true;
  72868. }
  72869. else {
  72870. p = p.next;
  72871. }
  72872. } while (again || p !== end);
  72873. return end;
  72874. }
  72875. // main ear slicing loop which triangulates a polygon (given as a linked list)
  72876. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  72877. if (!ear)
  72878. return;
  72879. // interlink polygon nodes in z-order
  72880. if (!pass && size)
  72881. indexCurve(ear, minX, minY, size);
  72882. var stop = ear, prev, next;
  72883. // iterate through ears, slicing them one by one
  72884. while (ear.prev !== ear.next) {
  72885. prev = ear.prev;
  72886. next = ear.next;
  72887. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  72888. // cut off the triangle
  72889. triangles.push(prev.i / dim);
  72890. triangles.push(ear.i / dim);
  72891. triangles.push(next.i / dim);
  72892. removeNode(ear);
  72893. // skipping the next vertice leads to less sliver triangles
  72894. ear = next.next;
  72895. stop = next.next;
  72896. continue;
  72897. }
  72898. ear = next;
  72899. // if we looped through the whole remaining polygon and can't find any more ears
  72900. if (ear === stop) {
  72901. // try filtering points and slicing again
  72902. if (!pass) {
  72903. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  72904. // if this didn't work, try curing all small self-intersections locally
  72905. }
  72906. else if (pass === 1) {
  72907. ear = cureLocalIntersections(ear, triangles, dim);
  72908. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  72909. // as a last resort, try splitting the remaining polygon into two
  72910. }
  72911. else if (pass === 2) {
  72912. splitEarcut(ear, triangles, dim, minX, minY, size);
  72913. }
  72914. break;
  72915. }
  72916. }
  72917. }
  72918. // check whether a polygon node forms a valid ear with adjacent nodes
  72919. function isEar(ear) {
  72920. var a = ear.prev, b = ear, c = ear.next;
  72921. if (area(a, b, c) >= 0)
  72922. return false; // reflex, can't be an ear
  72923. // now make sure we don't have other points inside the potential ear
  72924. var p = ear.next.next;
  72925. while (p !== ear.prev) {
  72926. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72927. area(p.prev, p, p.next) >= 0)
  72928. return false;
  72929. p = p.next;
  72930. }
  72931. return true;
  72932. }
  72933. function isEarHashed(ear, minX, minY, size) {
  72934. var a = ear.prev, b = ear, c = ear.next;
  72935. if (area(a, b, c) >= 0)
  72936. return false; // reflex, can't be an ear
  72937. // triangle bbox; min & max are calculated like this for speed
  72938. 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);
  72939. // z-order range for the current triangle bbox;
  72940. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  72941. // first look for points inside the triangle in increasing z-order
  72942. var p = ear.nextZ;
  72943. while (p && p.z <= maxZ) {
  72944. if (p !== ear.prev &&
  72945. p !== ear.next &&
  72946. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72947. area(p.prev, p, p.next) >= 0)
  72948. return false;
  72949. p = p.nextZ;
  72950. }
  72951. // then look for points in decreasing z-order
  72952. p = ear.prevZ;
  72953. while (p && p.z >= minZ) {
  72954. if (p !== ear.prev &&
  72955. p !== ear.next &&
  72956. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72957. area(p.prev, p, p.next) >= 0)
  72958. return false;
  72959. p = p.prevZ;
  72960. }
  72961. return true;
  72962. }
  72963. // go through all polygon nodes and cure small local self-intersections
  72964. function cureLocalIntersections(start, triangles, dim) {
  72965. var p = start;
  72966. do {
  72967. var a = p.prev, b = p.next.next;
  72968. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  72969. triangles.push(a.i / dim);
  72970. triangles.push(p.i / dim);
  72971. triangles.push(b.i / dim);
  72972. // remove two nodes involved
  72973. removeNode(p);
  72974. removeNode(p.next);
  72975. p = start = b;
  72976. }
  72977. p = p.next;
  72978. } while (p !== start);
  72979. return p;
  72980. }
  72981. // try splitting polygon into two and triangulate them independently
  72982. function splitEarcut(start, triangles, dim, minX, minY, size) {
  72983. // look for a valid diagonal that divides the polygon into two
  72984. var a = start;
  72985. do {
  72986. var b = a.next.next;
  72987. while (b !== a.prev) {
  72988. if (a.i !== b.i && isValidDiagonal(a, b)) {
  72989. // split the polygon in two by the diagonal
  72990. var c = splitPolygon(a, b);
  72991. // filter colinear points around the cuts
  72992. a = filterPoints(a, a.next);
  72993. c = filterPoints(c, c.next);
  72994. // run earcut on each half
  72995. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  72996. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  72997. return;
  72998. }
  72999. b = b.next;
  73000. }
  73001. a = a.next;
  73002. } while (a !== start);
  73003. }
  73004. // link every hole into the outer loop, producing a single-ring polygon without holes
  73005. function eliminateHoles(data, holeIndices, outerNode, dim) {
  73006. var queue = [], i, len, start, end, list;
  73007. for (i = 0, len = holeIndices.length; i < len; i++) {
  73008. start = holeIndices[i] * dim;
  73009. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73010. list = linkedList(data, start, end, dim, false);
  73011. if (list === list.next)
  73012. list.steiner = true;
  73013. queue.push(getLeftmost(list));
  73014. }
  73015. queue.sort(compareX);
  73016. // process holes from left to right
  73017. for (i = 0; i < queue.length; i++) {
  73018. eliminateHole(queue[i], outerNode);
  73019. outerNode = filterPoints(outerNode, outerNode.next);
  73020. }
  73021. return outerNode;
  73022. }
  73023. function compareX(a, b) {
  73024. return a.x - b.x;
  73025. }
  73026. // find a bridge between vertices that connects hole with an outer ring and and link it
  73027. function eliminateHole(hole, outerNode) {
  73028. outerNode = findHoleBridge(hole, outerNode);
  73029. if (outerNode) {
  73030. var b = splitPolygon(outerNode, hole);
  73031. filterPoints(b, b.next);
  73032. }
  73033. }
  73034. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  73035. function findHoleBridge(hole, outerNode) {
  73036. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  73037. // find a segment intersected by a ray from the hole's leftmost point to the left;
  73038. // segment's endpoint with lesser x will be potential connection point
  73039. do {
  73040. if (hy <= p.y && hy >= p.next.y) {
  73041. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  73042. if (x <= hx && x > qx) {
  73043. qx = x;
  73044. if (x === hx) {
  73045. if (hy === p.y)
  73046. return p;
  73047. if (hy === p.next.y)
  73048. return p.next;
  73049. }
  73050. m = p.x < p.next.x ? p : p.next;
  73051. }
  73052. }
  73053. p = p.next;
  73054. } while (p !== outerNode);
  73055. if (!m)
  73056. return null;
  73057. if (hx === qx)
  73058. return m.prev; // hole touches outer segment; pick lower endpoint
  73059. // look for points inside the triangle of hole point, segment intersection and endpoint;
  73060. // if there are no points found, we have a valid connection;
  73061. // otherwise choose the point of the minimum angle with the ray as connection point
  73062. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  73063. p = m.next;
  73064. while (p !== stop) {
  73065. if (hx >= p.x &&
  73066. p.x >= mx &&
  73067. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  73068. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  73069. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  73070. m = p;
  73071. tanMin = tan;
  73072. }
  73073. }
  73074. p = p.next;
  73075. }
  73076. return m;
  73077. }
  73078. // interlink polygon nodes in z-order
  73079. function indexCurve(start, minX, minY, size) {
  73080. var p = start;
  73081. do {
  73082. if (p.z === null)
  73083. p.z = zOrder(p.x, p.y, minX, minY, size);
  73084. p.prevZ = p.prev;
  73085. p.nextZ = p.next;
  73086. p = p.next;
  73087. } while (p !== start);
  73088. p.prevZ.nextZ = null;
  73089. p.prevZ = null;
  73090. sortLinked(p);
  73091. }
  73092. // Simon Tatham's linked list merge sort algorithm
  73093. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  73094. function sortLinked(list) {
  73095. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  73096. do {
  73097. p = list;
  73098. list = null;
  73099. tail = null;
  73100. numMerges = 0;
  73101. while (p) {
  73102. numMerges++;
  73103. q = p;
  73104. pSize = 0;
  73105. for (i = 0; i < inSize; i++) {
  73106. pSize++;
  73107. q = q.nextZ;
  73108. if (!q)
  73109. break;
  73110. }
  73111. qSize = inSize;
  73112. while (pSize > 0 || (qSize > 0 && q)) {
  73113. if (pSize === 0) {
  73114. e = q;
  73115. q = q.nextZ;
  73116. qSize--;
  73117. }
  73118. else if (qSize === 0 || !q) {
  73119. e = p;
  73120. p = p.nextZ;
  73121. pSize--;
  73122. }
  73123. else if (p.z <= q.z) {
  73124. e = p;
  73125. p = p.nextZ;
  73126. pSize--;
  73127. }
  73128. else {
  73129. e = q;
  73130. q = q.nextZ;
  73131. qSize--;
  73132. }
  73133. if (tail)
  73134. tail.nextZ = e;
  73135. else
  73136. list = e;
  73137. e.prevZ = tail;
  73138. tail = e;
  73139. }
  73140. p = q;
  73141. }
  73142. tail.nextZ = null;
  73143. inSize *= 2;
  73144. } while (numMerges > 1);
  73145. return list;
  73146. }
  73147. // z-order of a point given coords and size of the data bounding box
  73148. function zOrder(x, y, minX, minY, size) {
  73149. // coords are transformed into non-negative 15-bit integer range
  73150. x = 32767 * (x - minX) / size;
  73151. y = 32767 * (y - minY) / size;
  73152. x = (x | (x << 8)) & 0x00FF00FF;
  73153. x = (x | (x << 4)) & 0x0F0F0F0F;
  73154. x = (x | (x << 2)) & 0x33333333;
  73155. x = (x | (x << 1)) & 0x55555555;
  73156. y = (y | (y << 8)) & 0x00FF00FF;
  73157. y = (y | (y << 4)) & 0x0F0F0F0F;
  73158. y = (y | (y << 2)) & 0x33333333;
  73159. y = (y | (y << 1)) & 0x55555555;
  73160. return x | (y << 1);
  73161. }
  73162. // find the leftmost node of a polygon ring
  73163. function getLeftmost(start) {
  73164. var p = start, leftmost = start;
  73165. do {
  73166. if (p.x < leftmost.x)
  73167. leftmost = p;
  73168. p = p.next;
  73169. } while (p !== start);
  73170. return leftmost;
  73171. }
  73172. // check if a point lies within a convex triangle
  73173. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  73174. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  73175. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  73176. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  73177. }
  73178. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  73179. function isValidDiagonal(a, b) {
  73180. return a.next.i !== b.i &&
  73181. a.prev.i !== b.i &&
  73182. !intersectsPolygon(a, b) &&
  73183. locallyInside(a, b) &&
  73184. locallyInside(b, a) &&
  73185. middleInside(a, b);
  73186. }
  73187. // signed area of a triangle
  73188. function area(p, q, r) {
  73189. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  73190. }
  73191. // check if two points are equal
  73192. function equals(p1, p2) {
  73193. return p1.x === p2.x && p1.y === p2.y;
  73194. }
  73195. // check if two segments intersect
  73196. function intersects(p1, q1, p2, q2) {
  73197. if ((equals(p1, q1) && equals(p2, q2)) ||
  73198. (equals(p1, q2) && equals(p2, q1)))
  73199. return true;
  73200. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  73201. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  73202. }
  73203. // check if a polygon diagonal intersects any polygon segments
  73204. function intersectsPolygon(a, b) {
  73205. var p = a;
  73206. do {
  73207. if (p.i !== a.i &&
  73208. p.next.i !== a.i &&
  73209. p.i !== b.i &&
  73210. p.next.i !== b.i &&
  73211. intersects(p, p.next, a, b))
  73212. return true;
  73213. p = p.next;
  73214. } while (p !== a);
  73215. return false;
  73216. }
  73217. // check if a polygon diagonal is locally inside the polygon
  73218. function locallyInside(a, b) {
  73219. return area(a.prev, a, a.next) < 0
  73220. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  73221. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  73222. }
  73223. // check if the middle point of a polygon diagonal is inside the polygon
  73224. function middleInside(a, b) {
  73225. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  73226. do {
  73227. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  73228. inside = !inside;
  73229. p = p.next;
  73230. } while (p !== a);
  73231. return inside;
  73232. }
  73233. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  73234. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  73235. function splitPolygon(a, b) {
  73236. 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;
  73237. a.next = b;
  73238. b.prev = a;
  73239. a2.next = an;
  73240. an.prev = a2;
  73241. b2.next = a2;
  73242. a2.prev = b2;
  73243. bp.next = b2;
  73244. b2.prev = bp;
  73245. return b2;
  73246. }
  73247. // create a node and optionally link it with previous one (in a circular doubly linked list)
  73248. function insertNode(i, x, y, last) {
  73249. var p = new Node(i, x, y);
  73250. if (!last) {
  73251. p.prev = p;
  73252. p.next = p;
  73253. }
  73254. else {
  73255. p.next = last.next;
  73256. p.prev = last;
  73257. last.next.prev = p;
  73258. last.next = p;
  73259. }
  73260. return p;
  73261. }
  73262. function removeNode(p) {
  73263. p.next.prev = p.prev;
  73264. p.prev.next = p.next;
  73265. if (p.prevZ)
  73266. p.prevZ.nextZ = p.nextZ;
  73267. if (p.nextZ)
  73268. p.nextZ.prevZ = p.prevZ;
  73269. }
  73270. /**
  73271. * return a percentage difference between the polygon area and its triangulation area;
  73272. * used to verify correctness of triangulation
  73273. */
  73274. function deviation(data, holeIndices, dim, triangles) {
  73275. var hasHoles = holeIndices && holeIndices.length;
  73276. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  73277. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  73278. if (hasHoles) {
  73279. for (var i = 0, len = holeIndices.length; i < len; i++) {
  73280. var start = holeIndices[i] * dim;
  73281. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73282. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  73283. }
  73284. }
  73285. var trianglesArea = 0;
  73286. for (i = 0; i < triangles.length; i += 3) {
  73287. var a = triangles[i] * dim;
  73288. var b = triangles[i + 1] * dim;
  73289. var c = triangles[i + 2] * dim;
  73290. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  73291. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  73292. }
  73293. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  73294. }
  73295. Earcut.deviation = deviation;
  73296. ;
  73297. function signedArea(data, start, end, dim) {
  73298. var sum = 0;
  73299. for (var i = start, j = end - dim; i < end; i += dim) {
  73300. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  73301. j = i;
  73302. }
  73303. return sum;
  73304. }
  73305. /**
  73306. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  73307. */
  73308. function flatten(data) {
  73309. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  73310. for (var i = 0; i < data.length; i++) {
  73311. for (var j = 0; j < data[i].length; j++) {
  73312. for (var d = 0; d < dim; d++)
  73313. result.vertices.push(data[i][j][d]);
  73314. }
  73315. if (i > 0) {
  73316. holeIndex += data[i - 1].length;
  73317. result.holes.push(holeIndex);
  73318. }
  73319. }
  73320. return result;
  73321. }
  73322. Earcut.flatten = flatten;
  73323. ;
  73324. })(Earcut || (Earcut = {}));
  73325. //# sourceMappingURL=babylon.earcut.js.map
  73326. var BABYLON;
  73327. (function (BABYLON) {
  73328. var IndexedVector2 = /** @class */ (function (_super) {
  73329. __extends(IndexedVector2, _super);
  73330. function IndexedVector2(original, index) {
  73331. var _this = _super.call(this, original.x, original.y) || this;
  73332. _this.index = index;
  73333. return _this;
  73334. }
  73335. return IndexedVector2;
  73336. }(BABYLON.Vector2));
  73337. var PolygonPoints = /** @class */ (function () {
  73338. function PolygonPoints() {
  73339. this.elements = new Array();
  73340. }
  73341. PolygonPoints.prototype.add = function (originalPoints) {
  73342. var _this = this;
  73343. var result = new Array();
  73344. originalPoints.forEach(function (point) {
  73345. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  73346. var newPoint = new IndexedVector2(point, _this.elements.length);
  73347. result.push(newPoint);
  73348. _this.elements.push(newPoint);
  73349. }
  73350. });
  73351. return result;
  73352. };
  73353. PolygonPoints.prototype.computeBounds = function () {
  73354. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73355. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73356. this.elements.forEach(function (point) {
  73357. // x
  73358. if (point.x < lmin.x) {
  73359. lmin.x = point.x;
  73360. }
  73361. else if (point.x > lmax.x) {
  73362. lmax.x = point.x;
  73363. }
  73364. // y
  73365. if (point.y < lmin.y) {
  73366. lmin.y = point.y;
  73367. }
  73368. else if (point.y > lmax.y) {
  73369. lmax.y = point.y;
  73370. }
  73371. });
  73372. return {
  73373. min: lmin,
  73374. max: lmax,
  73375. width: lmax.x - lmin.x,
  73376. height: lmax.y - lmin.y
  73377. };
  73378. };
  73379. return PolygonPoints;
  73380. }());
  73381. var Polygon = /** @class */ (function () {
  73382. function Polygon() {
  73383. }
  73384. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  73385. return [
  73386. new BABYLON.Vector2(xmin, ymin),
  73387. new BABYLON.Vector2(xmax, ymin),
  73388. new BABYLON.Vector2(xmax, ymax),
  73389. new BABYLON.Vector2(xmin, ymax)
  73390. ];
  73391. };
  73392. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  73393. if (cx === void 0) { cx = 0; }
  73394. if (cy === void 0) { cy = 0; }
  73395. if (numberOfSides === void 0) { numberOfSides = 32; }
  73396. var result = new Array();
  73397. var angle = 0;
  73398. var increment = (Math.PI * 2) / numberOfSides;
  73399. for (var i = 0; i < numberOfSides; i++) {
  73400. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  73401. angle -= increment;
  73402. }
  73403. return result;
  73404. };
  73405. Polygon.Parse = function (input) {
  73406. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  73407. var i, result = [];
  73408. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  73409. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  73410. }
  73411. return result;
  73412. };
  73413. Polygon.StartingAt = function (x, y) {
  73414. return BABYLON.Path2.StartingAt(x, y);
  73415. };
  73416. return Polygon;
  73417. }());
  73418. BABYLON.Polygon = Polygon;
  73419. var PolygonMeshBuilder = /** @class */ (function () {
  73420. function PolygonMeshBuilder(name, contours, scene) {
  73421. this._points = new PolygonPoints();
  73422. this._outlinepoints = new PolygonPoints();
  73423. this._holes = new Array();
  73424. this._epoints = new Array();
  73425. this._eholes = new Array();
  73426. this._name = name;
  73427. this._scene = scene;
  73428. var points;
  73429. if (contours instanceof BABYLON.Path2) {
  73430. points = contours.getPoints();
  73431. }
  73432. else {
  73433. points = contours;
  73434. }
  73435. this._addToepoint(points);
  73436. this._points.add(points);
  73437. this._outlinepoints.add(points);
  73438. }
  73439. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  73440. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  73441. var p = points_1[_i];
  73442. this._epoints.push(p.x, p.y);
  73443. }
  73444. };
  73445. PolygonMeshBuilder.prototype.addHole = function (hole) {
  73446. this._points.add(hole);
  73447. var holepoints = new PolygonPoints();
  73448. holepoints.add(hole);
  73449. this._holes.push(holepoints);
  73450. this._eholes.push(this._epoints.length / 2);
  73451. this._addToepoint(hole);
  73452. return this;
  73453. };
  73454. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  73455. var _this = this;
  73456. if (updatable === void 0) { updatable = false; }
  73457. if (depth === void 0) { depth = 0; }
  73458. var result = new BABYLON.Mesh(this._name, this._scene);
  73459. var normals = new Array();
  73460. var positions = new Array();
  73461. var uvs = new Array();
  73462. var bounds = this._points.computeBounds();
  73463. this._points.elements.forEach(function (p) {
  73464. normals.push(0, 1.0, 0);
  73465. positions.push(p.x, 0, p.y);
  73466. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  73467. });
  73468. var indices = new Array();
  73469. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  73470. for (var i = 0; i < res.length; i++) {
  73471. indices.push(res[i]);
  73472. }
  73473. if (depth > 0) {
  73474. var positionscount = (positions.length / 3); //get the current pointcount
  73475. this._points.elements.forEach(function (p) {
  73476. normals.push(0, -1.0, 0);
  73477. positions.push(p.x, -depth, p.y);
  73478. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  73479. });
  73480. var totalCount = indices.length;
  73481. for (var i = 0; i < totalCount; i += 3) {
  73482. var i0 = indices[i + 0];
  73483. var i1 = indices[i + 1];
  73484. var i2 = indices[i + 2];
  73485. indices.push(i2 + positionscount);
  73486. indices.push(i1 + positionscount);
  73487. indices.push(i0 + positionscount);
  73488. }
  73489. //Add the sides
  73490. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  73491. this._holes.forEach(function (hole) {
  73492. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  73493. });
  73494. }
  73495. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  73496. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  73497. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  73498. result.setIndices(indices);
  73499. return result;
  73500. };
  73501. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  73502. var StartIndex = positions.length / 3;
  73503. var ulength = 0;
  73504. for (var i = 0; i < points.elements.length; i++) {
  73505. var p = points.elements[i];
  73506. var p1;
  73507. if ((i + 1) > points.elements.length - 1) {
  73508. p1 = points.elements[0];
  73509. }
  73510. else {
  73511. p1 = points.elements[i + 1];
  73512. }
  73513. positions.push(p.x, 0, p.y);
  73514. positions.push(p.x, -depth, p.y);
  73515. positions.push(p1.x, 0, p1.y);
  73516. positions.push(p1.x, -depth, p1.y);
  73517. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  73518. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  73519. var v3 = v2.subtract(v1);
  73520. var v4 = new BABYLON.Vector3(0, 1, 0);
  73521. var vn = BABYLON.Vector3.Cross(v3, v4);
  73522. vn = vn.normalize();
  73523. uvs.push(ulength / bounds.width, 0);
  73524. uvs.push(ulength / bounds.width, 1);
  73525. ulength += v3.length();
  73526. uvs.push((ulength / bounds.width), 0);
  73527. uvs.push((ulength / bounds.width), 1);
  73528. if (!flip) {
  73529. normals.push(-vn.x, -vn.y, -vn.z);
  73530. normals.push(-vn.x, -vn.y, -vn.z);
  73531. normals.push(-vn.x, -vn.y, -vn.z);
  73532. normals.push(-vn.x, -vn.y, -vn.z);
  73533. indices.push(StartIndex);
  73534. indices.push(StartIndex + 1);
  73535. indices.push(StartIndex + 2);
  73536. indices.push(StartIndex + 1);
  73537. indices.push(StartIndex + 3);
  73538. indices.push(StartIndex + 2);
  73539. }
  73540. else {
  73541. normals.push(vn.x, vn.y, vn.z);
  73542. normals.push(vn.x, vn.y, vn.z);
  73543. normals.push(vn.x, vn.y, vn.z);
  73544. normals.push(vn.x, vn.y, vn.z);
  73545. indices.push(StartIndex);
  73546. indices.push(StartIndex + 2);
  73547. indices.push(StartIndex + 1);
  73548. indices.push(StartIndex + 1);
  73549. indices.push(StartIndex + 2);
  73550. indices.push(StartIndex + 3);
  73551. }
  73552. StartIndex += 4;
  73553. }
  73554. ;
  73555. };
  73556. return PolygonMeshBuilder;
  73557. }());
  73558. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  73559. })(BABYLON || (BABYLON = {}));
  73560. //# sourceMappingURL=babylon.polygonMesh.js.map
  73561. var BABYLON;
  73562. (function (BABYLON) {
  73563. // Unique ID when we import meshes from Babylon to CSG
  73564. var currentCSGMeshId = 0;
  73565. // # class Vertex
  73566. // Represents a vertex of a polygon. Use your own vertex class instead of this
  73567. // one to provide additional features like texture coordinates and vertex
  73568. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  73569. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  73570. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  73571. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  73572. // is not used anywhere else.
  73573. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  73574. var Vertex = /** @class */ (function () {
  73575. function Vertex(pos, normal, uv) {
  73576. this.pos = pos;
  73577. this.normal = normal;
  73578. this.uv = uv;
  73579. }
  73580. Vertex.prototype.clone = function () {
  73581. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  73582. };
  73583. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  73584. // orientation of a polygon is flipped.
  73585. Vertex.prototype.flip = function () {
  73586. this.normal = this.normal.scale(-1);
  73587. };
  73588. // Create a new vertex between this vertex and `other` by linearly
  73589. // interpolating all properties using a parameter of `t`. Subclasses should
  73590. // override this to interpolate additional properties.
  73591. Vertex.prototype.interpolate = function (other, t) {
  73592. 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));
  73593. };
  73594. return Vertex;
  73595. }());
  73596. // # class Plane
  73597. // Represents a plane in 3D space.
  73598. var Plane = /** @class */ (function () {
  73599. function Plane(normal, w) {
  73600. this.normal = normal;
  73601. this.w = w;
  73602. }
  73603. Plane.FromPoints = function (a, b, c) {
  73604. var v0 = c.subtract(a);
  73605. var v1 = b.subtract(a);
  73606. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  73607. return null;
  73608. }
  73609. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  73610. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  73611. };
  73612. Plane.prototype.clone = function () {
  73613. return new Plane(this.normal.clone(), this.w);
  73614. };
  73615. Plane.prototype.flip = function () {
  73616. this.normal.scaleInPlace(-1);
  73617. this.w = -this.w;
  73618. };
  73619. // Split `polygon` by this plane if needed, then put the polygon or polygon
  73620. // fragments in the appropriate lists. Coplanar polygons go into either
  73621. // `coplanarFront` or `coplanarBack` depending on their orientation with
  73622. // respect to this plane. Polygons in front or in back of this plane go into
  73623. // either `front` or `back`.
  73624. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  73625. var COPLANAR = 0;
  73626. var FRONT = 1;
  73627. var BACK = 2;
  73628. var SPANNING = 3;
  73629. // Classify each point as well as the entire polygon into one of the above
  73630. // four classes.
  73631. var polygonType = 0;
  73632. var types = [];
  73633. var i;
  73634. var t;
  73635. for (i = 0; i < polygon.vertices.length; i++) {
  73636. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  73637. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  73638. polygonType |= type;
  73639. types.push(type);
  73640. }
  73641. // Put the polygon in the correct list, splitting it when necessary.
  73642. switch (polygonType) {
  73643. case COPLANAR:
  73644. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  73645. break;
  73646. case FRONT:
  73647. front.push(polygon);
  73648. break;
  73649. case BACK:
  73650. back.push(polygon);
  73651. break;
  73652. case SPANNING:
  73653. var f = [], b = [];
  73654. for (i = 0; i < polygon.vertices.length; i++) {
  73655. var j = (i + 1) % polygon.vertices.length;
  73656. var ti = types[i], tj = types[j];
  73657. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  73658. if (ti !== BACK)
  73659. f.push(vi);
  73660. if (ti !== FRONT)
  73661. b.push(ti !== BACK ? vi.clone() : vi);
  73662. if ((ti | tj) === SPANNING) {
  73663. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  73664. var v = vi.interpolate(vj, t);
  73665. f.push(v);
  73666. b.push(v.clone());
  73667. }
  73668. }
  73669. var poly;
  73670. if (f.length >= 3) {
  73671. poly = new Polygon(f, polygon.shared);
  73672. if (poly.plane)
  73673. front.push(poly);
  73674. }
  73675. if (b.length >= 3) {
  73676. poly = new Polygon(b, polygon.shared);
  73677. if (poly.plane)
  73678. back.push(poly);
  73679. }
  73680. break;
  73681. }
  73682. };
  73683. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  73684. // point is on the plane.
  73685. Plane.EPSILON = 1e-5;
  73686. return Plane;
  73687. }());
  73688. // # class Polygon
  73689. // Represents a convex polygon. The vertices used to initialize a polygon must
  73690. // be coplanar and form a convex loop.
  73691. //
  73692. // Each convex polygon has a `shared` property, which is shared between all
  73693. // polygons that are clones of each other or were split from the same polygon.
  73694. // This can be used to define per-polygon properties (such as surface color).
  73695. var Polygon = /** @class */ (function () {
  73696. function Polygon(vertices, shared) {
  73697. this.vertices = vertices;
  73698. this.shared = shared;
  73699. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  73700. }
  73701. Polygon.prototype.clone = function () {
  73702. var vertices = this.vertices.map(function (v) { return v.clone(); });
  73703. return new Polygon(vertices, this.shared);
  73704. };
  73705. Polygon.prototype.flip = function () {
  73706. this.vertices.reverse().map(function (v) { v.flip(); });
  73707. this.plane.flip();
  73708. };
  73709. return Polygon;
  73710. }());
  73711. // # class Node
  73712. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  73713. // by picking a polygon to split along. That polygon (and all other coplanar
  73714. // polygons) are added directly to that node and the other polygons are added to
  73715. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  73716. // no distinction between internal and leaf nodes.
  73717. var Node = /** @class */ (function () {
  73718. function Node(polygons) {
  73719. this.plane = null;
  73720. this.front = null;
  73721. this.back = null;
  73722. this.polygons = new Array();
  73723. if (polygons) {
  73724. this.build(polygons);
  73725. }
  73726. }
  73727. Node.prototype.clone = function () {
  73728. var node = new Node();
  73729. node.plane = this.plane && this.plane.clone();
  73730. node.front = this.front && this.front.clone();
  73731. node.back = this.back && this.back.clone();
  73732. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  73733. return node;
  73734. };
  73735. // Convert solid space to empty space and empty space to solid space.
  73736. Node.prototype.invert = function () {
  73737. for (var i = 0; i < this.polygons.length; i++) {
  73738. this.polygons[i].flip();
  73739. }
  73740. if (this.plane) {
  73741. this.plane.flip();
  73742. }
  73743. if (this.front) {
  73744. this.front.invert();
  73745. }
  73746. if (this.back) {
  73747. this.back.invert();
  73748. }
  73749. var temp = this.front;
  73750. this.front = this.back;
  73751. this.back = temp;
  73752. };
  73753. // Recursively remove all polygons in `polygons` that are inside this BSP
  73754. // tree.
  73755. Node.prototype.clipPolygons = function (polygons) {
  73756. if (!this.plane)
  73757. return polygons.slice();
  73758. var front = new Array(), back = new Array();
  73759. for (var i = 0; i < polygons.length; i++) {
  73760. this.plane.splitPolygon(polygons[i], front, back, front, back);
  73761. }
  73762. if (this.front) {
  73763. front = this.front.clipPolygons(front);
  73764. }
  73765. if (this.back) {
  73766. back = this.back.clipPolygons(back);
  73767. }
  73768. else {
  73769. back = [];
  73770. }
  73771. return front.concat(back);
  73772. };
  73773. // Remove all polygons in this BSP tree that are inside the other BSP tree
  73774. // `bsp`.
  73775. Node.prototype.clipTo = function (bsp) {
  73776. this.polygons = bsp.clipPolygons(this.polygons);
  73777. if (this.front)
  73778. this.front.clipTo(bsp);
  73779. if (this.back)
  73780. this.back.clipTo(bsp);
  73781. };
  73782. // Return a list of all polygons in this BSP tree.
  73783. Node.prototype.allPolygons = function () {
  73784. var polygons = this.polygons.slice();
  73785. if (this.front)
  73786. polygons = polygons.concat(this.front.allPolygons());
  73787. if (this.back)
  73788. polygons = polygons.concat(this.back.allPolygons());
  73789. return polygons;
  73790. };
  73791. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  73792. // new polygons are filtered down to the bottom of the tree and become new
  73793. // nodes there. Each set of polygons is partitioned using the first polygon
  73794. // (no heuristic is used to pick a good split).
  73795. Node.prototype.build = function (polygons) {
  73796. if (!polygons.length)
  73797. return;
  73798. if (!this.plane)
  73799. this.plane = polygons[0].plane.clone();
  73800. var front = new Array(), back = new Array();
  73801. for (var i = 0; i < polygons.length; i++) {
  73802. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  73803. }
  73804. if (front.length) {
  73805. if (!this.front)
  73806. this.front = new Node();
  73807. this.front.build(front);
  73808. }
  73809. if (back.length) {
  73810. if (!this.back)
  73811. this.back = new Node();
  73812. this.back.build(back);
  73813. }
  73814. };
  73815. return Node;
  73816. }());
  73817. var CSG = /** @class */ (function () {
  73818. function CSG() {
  73819. this.polygons = new Array();
  73820. }
  73821. // Convert BABYLON.Mesh to BABYLON.CSG
  73822. CSG.FromMesh = function (mesh) {
  73823. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  73824. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  73825. if (mesh instanceof BABYLON.Mesh) {
  73826. mesh.computeWorldMatrix(true);
  73827. matrix = mesh.getWorldMatrix();
  73828. meshPosition = mesh.position.clone();
  73829. meshRotation = mesh.rotation.clone();
  73830. if (mesh.rotationQuaternion) {
  73831. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  73832. }
  73833. meshScaling = mesh.scaling.clone();
  73834. }
  73835. else {
  73836. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  73837. }
  73838. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  73839. var subMeshes = mesh.subMeshes;
  73840. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  73841. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  73842. vertices = [];
  73843. for (var j = 0; j < 3; j++) {
  73844. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  73845. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  73846. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  73847. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  73848. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  73849. vertex = new Vertex(position, normal, uv);
  73850. vertices.push(vertex);
  73851. }
  73852. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  73853. // To handle the case of degenerated triangle
  73854. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  73855. if (polygon.plane)
  73856. polygons.push(polygon);
  73857. }
  73858. }
  73859. var csg = CSG.FromPolygons(polygons);
  73860. csg.matrix = matrix;
  73861. csg.position = meshPosition;
  73862. csg.rotation = meshRotation;
  73863. csg.scaling = meshScaling;
  73864. csg.rotationQuaternion = meshRotationQuaternion;
  73865. currentCSGMeshId++;
  73866. return csg;
  73867. };
  73868. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  73869. CSG.FromPolygons = function (polygons) {
  73870. var csg = new CSG();
  73871. csg.polygons = polygons;
  73872. return csg;
  73873. };
  73874. CSG.prototype.clone = function () {
  73875. var csg = new CSG();
  73876. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  73877. csg.copyTransformAttributes(this);
  73878. return csg;
  73879. };
  73880. CSG.prototype.union = function (csg) {
  73881. var a = new Node(this.clone().polygons);
  73882. var b = new Node(csg.clone().polygons);
  73883. a.clipTo(b);
  73884. b.clipTo(a);
  73885. b.invert();
  73886. b.clipTo(a);
  73887. b.invert();
  73888. a.build(b.allPolygons());
  73889. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73890. };
  73891. CSG.prototype.unionInPlace = function (csg) {
  73892. var a = new Node(this.polygons);
  73893. var b = new Node(csg.polygons);
  73894. a.clipTo(b);
  73895. b.clipTo(a);
  73896. b.invert();
  73897. b.clipTo(a);
  73898. b.invert();
  73899. a.build(b.allPolygons());
  73900. this.polygons = a.allPolygons();
  73901. };
  73902. CSG.prototype.subtract = function (csg) {
  73903. var a = new Node(this.clone().polygons);
  73904. var b = new Node(csg.clone().polygons);
  73905. a.invert();
  73906. a.clipTo(b);
  73907. b.clipTo(a);
  73908. b.invert();
  73909. b.clipTo(a);
  73910. b.invert();
  73911. a.build(b.allPolygons());
  73912. a.invert();
  73913. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73914. };
  73915. CSG.prototype.subtractInPlace = function (csg) {
  73916. var a = new Node(this.polygons);
  73917. var b = new Node(csg.polygons);
  73918. a.invert();
  73919. a.clipTo(b);
  73920. b.clipTo(a);
  73921. b.invert();
  73922. b.clipTo(a);
  73923. b.invert();
  73924. a.build(b.allPolygons());
  73925. a.invert();
  73926. this.polygons = a.allPolygons();
  73927. };
  73928. CSG.prototype.intersect = function (csg) {
  73929. var a = new Node(this.clone().polygons);
  73930. var b = new Node(csg.clone().polygons);
  73931. a.invert();
  73932. b.clipTo(a);
  73933. b.invert();
  73934. a.clipTo(b);
  73935. b.clipTo(a);
  73936. a.build(b.allPolygons());
  73937. a.invert();
  73938. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73939. };
  73940. CSG.prototype.intersectInPlace = function (csg) {
  73941. var a = new Node(this.polygons);
  73942. var b = new Node(csg.polygons);
  73943. a.invert();
  73944. b.clipTo(a);
  73945. b.invert();
  73946. a.clipTo(b);
  73947. b.clipTo(a);
  73948. a.build(b.allPolygons());
  73949. a.invert();
  73950. this.polygons = a.allPolygons();
  73951. };
  73952. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  73953. // not modified.
  73954. CSG.prototype.inverse = function () {
  73955. var csg = this.clone();
  73956. csg.inverseInPlace();
  73957. return csg;
  73958. };
  73959. CSG.prototype.inverseInPlace = function () {
  73960. this.polygons.map(function (p) { p.flip(); });
  73961. };
  73962. // This is used to keep meshes transformations so they can be restored
  73963. // when we build back a Babylon Mesh
  73964. // NB : All CSG operations are performed in world coordinates
  73965. CSG.prototype.copyTransformAttributes = function (csg) {
  73966. this.matrix = csg.matrix;
  73967. this.position = csg.position;
  73968. this.rotation = csg.rotation;
  73969. this.scaling = csg.scaling;
  73970. this.rotationQuaternion = csg.rotationQuaternion;
  73971. return this;
  73972. };
  73973. // Build Raw mesh from CSG
  73974. // Coordinates here are in world space
  73975. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  73976. var matrix = this.matrix.clone();
  73977. matrix.invert();
  73978. 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;
  73979. if (keepSubMeshes) {
  73980. // Sort Polygons, since subMeshes are indices range
  73981. polygons.sort(function (a, b) {
  73982. if (a.shared.meshId === b.shared.meshId) {
  73983. return a.shared.subMeshId - b.shared.subMeshId;
  73984. }
  73985. else {
  73986. return a.shared.meshId - b.shared.meshId;
  73987. }
  73988. });
  73989. }
  73990. for (var i = 0, il = polygons.length; i < il; i++) {
  73991. polygon = polygons[i];
  73992. // Building SubMeshes
  73993. if (!subMesh_dict[polygon.shared.meshId]) {
  73994. subMesh_dict[polygon.shared.meshId] = {};
  73995. }
  73996. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  73997. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  73998. indexStart: +Infinity,
  73999. indexEnd: -Infinity,
  74000. materialIndex: polygon.shared.materialIndex
  74001. };
  74002. }
  74003. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  74004. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  74005. polygonIndices[0] = 0;
  74006. polygonIndices[1] = j - 1;
  74007. polygonIndices[2] = j;
  74008. for (var k = 0; k < 3; k++) {
  74009. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  74010. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  74011. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  74012. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  74013. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  74014. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  74015. // Check if 2 points can be merged
  74016. if (!(typeof vertex_idx !== 'undefined' &&
  74017. normals[vertex_idx * 3] === localNormal.x &&
  74018. normals[vertex_idx * 3 + 1] === localNormal.y &&
  74019. normals[vertex_idx * 3 + 2] === localNormal.z &&
  74020. uvs[vertex_idx * 2] === uv.x &&
  74021. uvs[vertex_idx * 2 + 1] === uv.y)) {
  74022. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  74023. uvs.push(uv.x, uv.y);
  74024. normals.push(normal.x, normal.y, normal.z);
  74025. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  74026. }
  74027. indices.push(vertex_idx);
  74028. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  74029. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  74030. currentIndex++;
  74031. }
  74032. }
  74033. }
  74034. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  74035. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  74036. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  74037. mesh.setIndices(indices, null);
  74038. if (keepSubMeshes) {
  74039. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  74040. var materialIndexOffset = 0, materialMaxIndex;
  74041. mesh.subMeshes = new Array();
  74042. for (var m in subMesh_dict) {
  74043. materialMaxIndex = -1;
  74044. for (var sm in subMesh_dict[m]) {
  74045. subMesh_obj = subMesh_dict[m][sm];
  74046. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  74047. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  74048. }
  74049. materialIndexOffset += ++materialMaxIndex;
  74050. }
  74051. }
  74052. return mesh;
  74053. };
  74054. // Build Mesh from CSG taking material and transforms into account
  74055. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  74056. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  74057. mesh.material = material;
  74058. mesh.position.copyFrom(this.position);
  74059. mesh.rotation.copyFrom(this.rotation);
  74060. if (this.rotationQuaternion) {
  74061. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  74062. }
  74063. mesh.scaling.copyFrom(this.scaling);
  74064. mesh.computeWorldMatrix(true);
  74065. return mesh;
  74066. };
  74067. return CSG;
  74068. }());
  74069. BABYLON.CSG = CSG;
  74070. })(BABYLON || (BABYLON = {}));
  74071. //# sourceMappingURL=babylon.csg.js.map
  74072. var BABYLON;
  74073. (function (BABYLON) {
  74074. var LensFlare = /** @class */ (function () {
  74075. function LensFlare(size, position, color, imgUrl, system) {
  74076. this.size = size;
  74077. this.position = position;
  74078. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74079. this.color = color || new BABYLON.Color3(1, 1, 1);
  74080. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  74081. this._system = system;
  74082. system.lensFlares.push(this);
  74083. }
  74084. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  74085. return new LensFlare(size, position, color, imgUrl, system);
  74086. };
  74087. LensFlare.prototype.dispose = function () {
  74088. if (this.texture) {
  74089. this.texture.dispose();
  74090. }
  74091. // Remove from scene
  74092. var index = this._system.lensFlares.indexOf(this);
  74093. this._system.lensFlares.splice(index, 1);
  74094. };
  74095. ;
  74096. return LensFlare;
  74097. }());
  74098. BABYLON.LensFlare = LensFlare;
  74099. })(BABYLON || (BABYLON = {}));
  74100. //# sourceMappingURL=babylon.lensFlare.js.map
  74101. var BABYLON;
  74102. (function (BABYLON) {
  74103. var LensFlareSystem = /** @class */ (function () {
  74104. function LensFlareSystem(name, emitter, scene) {
  74105. this.name = name;
  74106. this.lensFlares = new Array();
  74107. this.borderLimit = 300;
  74108. this.viewportBorder = 0;
  74109. this.layerMask = 0x0FFFFFFF;
  74110. this._vertexBuffers = {};
  74111. this._isEnabled = true;
  74112. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74113. this._emitter = emitter;
  74114. this.id = name;
  74115. scene.lensFlareSystems.push(this);
  74116. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  74117. var engine = scene.getEngine();
  74118. // VBO
  74119. var vertices = [];
  74120. vertices.push(1, 1);
  74121. vertices.push(-1, 1);
  74122. vertices.push(-1, -1);
  74123. vertices.push(1, -1);
  74124. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74125. // Indices
  74126. var indices = [];
  74127. indices.push(0);
  74128. indices.push(1);
  74129. indices.push(2);
  74130. indices.push(0);
  74131. indices.push(2);
  74132. indices.push(3);
  74133. this._indexBuffer = engine.createIndexBuffer(indices);
  74134. // Effects
  74135. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  74136. }
  74137. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  74138. get: function () {
  74139. return this._isEnabled;
  74140. },
  74141. set: function (value) {
  74142. this._isEnabled = value;
  74143. },
  74144. enumerable: true,
  74145. configurable: true
  74146. });
  74147. LensFlareSystem.prototype.getScene = function () {
  74148. return this._scene;
  74149. };
  74150. LensFlareSystem.prototype.getEmitter = function () {
  74151. return this._emitter;
  74152. };
  74153. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  74154. this._emitter = newEmitter;
  74155. };
  74156. LensFlareSystem.prototype.getEmitterPosition = function () {
  74157. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  74158. };
  74159. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  74160. var position = this.getEmitterPosition();
  74161. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  74162. this._positionX = position.x;
  74163. this._positionY = position.y;
  74164. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  74165. if (this.viewportBorder > 0) {
  74166. globalViewport.x -= this.viewportBorder;
  74167. globalViewport.y -= this.viewportBorder;
  74168. globalViewport.width += this.viewportBorder * 2;
  74169. globalViewport.height += this.viewportBorder * 2;
  74170. position.x += this.viewportBorder;
  74171. position.y += this.viewportBorder;
  74172. this._positionX += this.viewportBorder;
  74173. this._positionY += this.viewportBorder;
  74174. }
  74175. if (position.z > 0) {
  74176. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  74177. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  74178. return true;
  74179. }
  74180. return true;
  74181. }
  74182. return false;
  74183. };
  74184. LensFlareSystem.prototype._isVisible = function () {
  74185. if (!this._isEnabled || !this._scene.activeCamera) {
  74186. return false;
  74187. }
  74188. var emitterPosition = this.getEmitterPosition();
  74189. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  74190. var distance = direction.length();
  74191. direction.normalize();
  74192. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  74193. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  74194. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  74195. };
  74196. LensFlareSystem.prototype.render = function () {
  74197. if (!this._effect.isReady() || !this._scene.activeCamera)
  74198. return false;
  74199. var engine = this._scene.getEngine();
  74200. var viewport = this._scene.activeCamera.viewport;
  74201. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  74202. // Position
  74203. if (!this.computeEffectivePosition(globalViewport)) {
  74204. return false;
  74205. }
  74206. // Visibility
  74207. if (!this._isVisible()) {
  74208. return false;
  74209. }
  74210. // Intensity
  74211. var awayX;
  74212. var awayY;
  74213. if (this._positionX < this.borderLimit + globalViewport.x) {
  74214. awayX = this.borderLimit + globalViewport.x - this._positionX;
  74215. }
  74216. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  74217. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  74218. }
  74219. else {
  74220. awayX = 0;
  74221. }
  74222. if (this._positionY < this.borderLimit + globalViewport.y) {
  74223. awayY = this.borderLimit + globalViewport.y - this._positionY;
  74224. }
  74225. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  74226. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  74227. }
  74228. else {
  74229. awayY = 0;
  74230. }
  74231. var away = (awayX > awayY) ? awayX : awayY;
  74232. away -= this.viewportBorder;
  74233. if (away > this.borderLimit) {
  74234. away = this.borderLimit;
  74235. }
  74236. var intensity = 1.0 - (away / this.borderLimit);
  74237. if (intensity < 0) {
  74238. return false;
  74239. }
  74240. if (intensity > 1.0) {
  74241. intensity = 1.0;
  74242. }
  74243. if (this.viewportBorder > 0) {
  74244. globalViewport.x += this.viewportBorder;
  74245. globalViewport.y += this.viewportBorder;
  74246. globalViewport.width -= this.viewportBorder * 2;
  74247. globalViewport.height -= this.viewportBorder * 2;
  74248. this._positionX -= this.viewportBorder;
  74249. this._positionY -= this.viewportBorder;
  74250. }
  74251. // Position
  74252. var centerX = globalViewport.x + globalViewport.width / 2;
  74253. var centerY = globalViewport.y + globalViewport.height / 2;
  74254. var distX = centerX - this._positionX;
  74255. var distY = centerY - this._positionY;
  74256. // Effects
  74257. engine.enableEffect(this._effect);
  74258. engine.setState(false);
  74259. engine.setDepthBuffer(false);
  74260. // VBOs
  74261. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74262. // Flares
  74263. for (var index = 0; index < this.lensFlares.length; index++) {
  74264. var flare = this.lensFlares[index];
  74265. engine.setAlphaMode(flare.alphaMode);
  74266. var x = centerX - (distX * flare.position);
  74267. var y = centerY - (distY * flare.position);
  74268. var cw = flare.size;
  74269. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  74270. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  74271. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  74272. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  74273. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  74274. // Texture
  74275. this._effect.setTexture("textureSampler", flare.texture);
  74276. // Color
  74277. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  74278. // Draw order
  74279. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74280. }
  74281. engine.setDepthBuffer(true);
  74282. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74283. return true;
  74284. };
  74285. LensFlareSystem.prototype.dispose = function () {
  74286. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74287. if (vertexBuffer) {
  74288. vertexBuffer.dispose();
  74289. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74290. }
  74291. if (this._indexBuffer) {
  74292. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74293. this._indexBuffer = null;
  74294. }
  74295. while (this.lensFlares.length) {
  74296. this.lensFlares[0].dispose();
  74297. }
  74298. // Remove from scene
  74299. var index = this._scene.lensFlareSystems.indexOf(this);
  74300. this._scene.lensFlareSystems.splice(index, 1);
  74301. };
  74302. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  74303. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  74304. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  74305. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  74306. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  74307. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  74308. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  74309. var parsedFlare = parsedLensFlareSystem.flares[index];
  74310. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  74311. }
  74312. return lensFlareSystem;
  74313. };
  74314. LensFlareSystem.prototype.serialize = function () {
  74315. var serializationObject = {};
  74316. serializationObject.id = this.id;
  74317. serializationObject.name = this.name;
  74318. serializationObject.emitterId = this.getEmitter().id;
  74319. serializationObject.borderLimit = this.borderLimit;
  74320. serializationObject.flares = [];
  74321. for (var index = 0; index < this.lensFlares.length; index++) {
  74322. var flare = this.lensFlares[index];
  74323. serializationObject.flares.push({
  74324. size: flare.size,
  74325. position: flare.position,
  74326. color: flare.color.asArray(),
  74327. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  74328. });
  74329. }
  74330. return serializationObject;
  74331. };
  74332. return LensFlareSystem;
  74333. }());
  74334. BABYLON.LensFlareSystem = LensFlareSystem;
  74335. })(BABYLON || (BABYLON = {}));
  74336. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  74337. var BABYLON;
  74338. (function (BABYLON) {
  74339. /**
  74340. * This is a holder class for the physics joint created by the physics plugin.
  74341. * It holds a set of functions to control the underlying joint.
  74342. */
  74343. var PhysicsJoint = /** @class */ (function () {
  74344. function PhysicsJoint(type, jointData) {
  74345. this.type = type;
  74346. this.jointData = jointData;
  74347. jointData.nativeParams = jointData.nativeParams || {};
  74348. }
  74349. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  74350. get: function () {
  74351. return this._physicsJoint;
  74352. },
  74353. set: function (newJoint) {
  74354. if (this._physicsJoint) {
  74355. //remove from the wolrd
  74356. }
  74357. this._physicsJoint = newJoint;
  74358. },
  74359. enumerable: true,
  74360. configurable: true
  74361. });
  74362. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  74363. set: function (physicsPlugin) {
  74364. this._physicsPlugin = physicsPlugin;
  74365. },
  74366. enumerable: true,
  74367. configurable: true
  74368. });
  74369. /**
  74370. * Execute a function that is physics-plugin specific.
  74371. * @param {Function} func the function that will be executed.
  74372. * It accepts two parameters: the physics world and the physics joint.
  74373. */
  74374. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  74375. func(this._physicsPlugin.world, this._physicsJoint);
  74376. };
  74377. //TODO check if the native joints are the same
  74378. //Joint Types
  74379. PhysicsJoint.DistanceJoint = 0;
  74380. PhysicsJoint.HingeJoint = 1;
  74381. PhysicsJoint.BallAndSocketJoint = 2;
  74382. PhysicsJoint.WheelJoint = 3;
  74383. PhysicsJoint.SliderJoint = 4;
  74384. //OIMO
  74385. PhysicsJoint.PrismaticJoint = 5;
  74386. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  74387. PhysicsJoint.UniversalJoint = 6;
  74388. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  74389. //Cannon
  74390. //Similar to a Ball-Joint. Different in params
  74391. PhysicsJoint.PointToPointJoint = 8;
  74392. //Cannon only at the moment
  74393. PhysicsJoint.SpringJoint = 9;
  74394. PhysicsJoint.LockJoint = 10;
  74395. return PhysicsJoint;
  74396. }());
  74397. BABYLON.PhysicsJoint = PhysicsJoint;
  74398. /**
  74399. * A class representing a physics distance joint.
  74400. */
  74401. var DistanceJoint = /** @class */ (function (_super) {
  74402. __extends(DistanceJoint, _super);
  74403. function DistanceJoint(jointData) {
  74404. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  74405. }
  74406. /**
  74407. * Update the predefined distance.
  74408. */
  74409. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  74410. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  74411. };
  74412. return DistanceJoint;
  74413. }(PhysicsJoint));
  74414. BABYLON.DistanceJoint = DistanceJoint;
  74415. var MotorEnabledJoint = /** @class */ (function (_super) {
  74416. __extends(MotorEnabledJoint, _super);
  74417. function MotorEnabledJoint(type, jointData) {
  74418. return _super.call(this, type, jointData) || this;
  74419. }
  74420. /**
  74421. * Set the motor values.
  74422. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74423. * @param {number} force the force to apply
  74424. * @param {number} maxForce max force for this motor.
  74425. */
  74426. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  74427. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74428. };
  74429. /**
  74430. * Set the motor's limits.
  74431. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74432. */
  74433. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74434. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74435. };
  74436. return MotorEnabledJoint;
  74437. }(PhysicsJoint));
  74438. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  74439. /**
  74440. * This class represents a single hinge physics joint
  74441. */
  74442. var HingeJoint = /** @class */ (function (_super) {
  74443. __extends(HingeJoint, _super);
  74444. function HingeJoint(jointData) {
  74445. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  74446. }
  74447. /**
  74448. * Set the motor values.
  74449. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74450. * @param {number} force the force to apply
  74451. * @param {number} maxForce max force for this motor.
  74452. */
  74453. HingeJoint.prototype.setMotor = function (force, maxForce) {
  74454. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74455. };
  74456. /**
  74457. * Set the motor's limits.
  74458. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74459. */
  74460. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74461. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74462. };
  74463. return HingeJoint;
  74464. }(MotorEnabledJoint));
  74465. BABYLON.HingeJoint = HingeJoint;
  74466. /**
  74467. * This class represents a dual hinge physics joint (same as wheel joint)
  74468. */
  74469. var Hinge2Joint = /** @class */ (function (_super) {
  74470. __extends(Hinge2Joint, _super);
  74471. function Hinge2Joint(jointData) {
  74472. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  74473. }
  74474. /**
  74475. * Set the motor values.
  74476. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74477. * @param {number} force the force to apply
  74478. * @param {number} maxForce max force for this motor.
  74479. * @param {motorIndex} the motor's index, 0 or 1.
  74480. */
  74481. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  74482. if (motorIndex === void 0) { motorIndex = 0; }
  74483. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  74484. };
  74485. /**
  74486. * Set the motor limits.
  74487. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74488. * @param {number} upperLimit the upper limit
  74489. * @param {number} lowerLimit lower limit
  74490. * @param {motorIndex} the motor's index, 0 or 1.
  74491. */
  74492. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  74493. if (motorIndex === void 0) { motorIndex = 0; }
  74494. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  74495. };
  74496. return Hinge2Joint;
  74497. }(MotorEnabledJoint));
  74498. BABYLON.Hinge2Joint = Hinge2Joint;
  74499. })(BABYLON || (BABYLON = {}));
  74500. //# sourceMappingURL=babylon.physicsJoint.js.map
  74501. var BABYLON;
  74502. (function (BABYLON) {
  74503. var PhysicsImpostor = /** @class */ (function () {
  74504. function PhysicsImpostor(object, type, _options, _scene) {
  74505. if (_options === void 0) { _options = { mass: 0 }; }
  74506. var _this = this;
  74507. this.object = object;
  74508. this.type = type;
  74509. this._options = _options;
  74510. this._scene = _scene;
  74511. this._bodyUpdateRequired = false;
  74512. this._onBeforePhysicsStepCallbacks = new Array();
  74513. this._onAfterPhysicsStepCallbacks = new Array();
  74514. this._onPhysicsCollideCallbacks = [];
  74515. this._deltaPosition = BABYLON.Vector3.Zero();
  74516. this._isDisposed = false;
  74517. //temp variables for parent rotation calculations
  74518. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  74519. this._tmpQuat = new BABYLON.Quaternion();
  74520. this._tmpQuat2 = new BABYLON.Quaternion();
  74521. /**
  74522. * this function is executed by the physics engine.
  74523. */
  74524. this.beforeStep = function () {
  74525. if (!_this._physicsEngine) {
  74526. return;
  74527. }
  74528. _this.object.translate(_this._deltaPosition, -1);
  74529. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  74530. _this.object.computeWorldMatrix(false);
  74531. if (_this.object.parent && _this.object.rotationQuaternion) {
  74532. _this.getParentsRotation();
  74533. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  74534. }
  74535. else {
  74536. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  74537. }
  74538. if (!_this._options.disableBidirectionalTransformation) {
  74539. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  74540. }
  74541. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  74542. func(_this);
  74543. });
  74544. };
  74545. /**
  74546. * this function is executed by the physics engine.
  74547. */
  74548. this.afterStep = function () {
  74549. if (!_this._physicsEngine) {
  74550. return;
  74551. }
  74552. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  74553. func(_this);
  74554. });
  74555. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  74556. // object has now its world rotation. needs to be converted to local.
  74557. if (_this.object.parent && _this.object.rotationQuaternion) {
  74558. _this.getParentsRotation();
  74559. _this._tmpQuat.conjugateInPlace();
  74560. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  74561. }
  74562. // take the position set and make it the absolute position of this object.
  74563. _this.object.setAbsolutePosition(_this.object.position);
  74564. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  74565. _this.object.translate(_this._deltaPosition, 1);
  74566. };
  74567. /**
  74568. * Legacy collision detection event support
  74569. */
  74570. this.onCollideEvent = null;
  74571. //event and body object due to cannon's event-based architecture.
  74572. this.onCollide = function (e) {
  74573. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  74574. return;
  74575. }
  74576. if (!_this._physicsEngine) {
  74577. return;
  74578. }
  74579. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  74580. if (otherImpostor) {
  74581. // Legacy collision detection event support
  74582. if (_this.onCollideEvent) {
  74583. _this.onCollideEvent(_this, otherImpostor);
  74584. }
  74585. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  74586. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  74587. }).forEach(function (obj) {
  74588. obj.callback(_this, otherImpostor);
  74589. });
  74590. }
  74591. };
  74592. //sanity check!
  74593. if (!this.object) {
  74594. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  74595. return;
  74596. }
  74597. //legacy support for old syntax.
  74598. if (!this._scene && object.getScene) {
  74599. this._scene = object.getScene();
  74600. }
  74601. if (!this._scene) {
  74602. return;
  74603. }
  74604. this._physicsEngine = this._scene.getPhysicsEngine();
  74605. if (!this._physicsEngine) {
  74606. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  74607. }
  74608. else {
  74609. //set the object's quaternion, if not set
  74610. if (!this.object.rotationQuaternion) {
  74611. if (this.object.rotation) {
  74612. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  74613. }
  74614. else {
  74615. this.object.rotationQuaternion = new BABYLON.Quaternion();
  74616. }
  74617. }
  74618. //default options params
  74619. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  74620. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  74621. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  74622. this._joints = [];
  74623. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  74624. if (!this.object.parent || this._options.ignoreParent) {
  74625. this._init();
  74626. }
  74627. else if (this.object.parent.physicsImpostor) {
  74628. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  74629. }
  74630. }
  74631. }
  74632. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  74633. get: function () {
  74634. return this._isDisposed;
  74635. },
  74636. enumerable: true,
  74637. configurable: true
  74638. });
  74639. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  74640. get: function () {
  74641. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  74642. },
  74643. set: function (value) {
  74644. this.setMass(value);
  74645. },
  74646. enumerable: true,
  74647. configurable: true
  74648. });
  74649. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  74650. get: function () {
  74651. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  74652. },
  74653. set: function (value) {
  74654. if (!this._physicsEngine) {
  74655. return;
  74656. }
  74657. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  74658. },
  74659. enumerable: true,
  74660. configurable: true
  74661. });
  74662. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  74663. get: function () {
  74664. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  74665. },
  74666. set: function (value) {
  74667. if (!this._physicsEngine) {
  74668. return;
  74669. }
  74670. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  74671. },
  74672. enumerable: true,
  74673. configurable: true
  74674. });
  74675. /**
  74676. * This function will completly initialize this impostor.
  74677. * It will create a new body - but only if this mesh has no parent.
  74678. * If it has, this impostor will not be used other than to define the impostor
  74679. * of the child mesh.
  74680. */
  74681. PhysicsImpostor.prototype._init = function () {
  74682. if (!this._physicsEngine) {
  74683. return;
  74684. }
  74685. this._physicsEngine.removeImpostor(this);
  74686. this.physicsBody = null;
  74687. this._parent = this._parent || this._getPhysicsParent();
  74688. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  74689. this._physicsEngine.addImpostor(this);
  74690. }
  74691. };
  74692. PhysicsImpostor.prototype._getPhysicsParent = function () {
  74693. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  74694. var parentMesh = this.object.parent;
  74695. return parentMesh.physicsImpostor;
  74696. }
  74697. return null;
  74698. };
  74699. /**
  74700. * Should a new body be generated.
  74701. */
  74702. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  74703. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  74704. };
  74705. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  74706. this.forceUpdate();
  74707. };
  74708. /**
  74709. * Force a regeneration of this or the parent's impostor's body.
  74710. * Use under cautious - This will remove all joints already implemented.
  74711. */
  74712. PhysicsImpostor.prototype.forceUpdate = function () {
  74713. this._init();
  74714. if (this.parent && !this._options.ignoreParent) {
  74715. this.parent.forceUpdate();
  74716. }
  74717. };
  74718. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  74719. /*public get mesh(): AbstractMesh {
  74720. return this._mesh;
  74721. }*/
  74722. /**
  74723. * Gets the body that holds this impostor. Either its own, or its parent.
  74724. */
  74725. get: function () {
  74726. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  74727. },
  74728. /**
  74729. * Set the physics body. Used mainly by the physics engine/plugin
  74730. */
  74731. set: function (physicsBody) {
  74732. if (this._physicsBody && this._physicsEngine) {
  74733. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  74734. }
  74735. this._physicsBody = physicsBody;
  74736. this.resetUpdateFlags();
  74737. },
  74738. enumerable: true,
  74739. configurable: true
  74740. });
  74741. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  74742. get: function () {
  74743. return !this._options.ignoreParent && this._parent ? this._parent : null;
  74744. },
  74745. set: function (value) {
  74746. this._parent = value;
  74747. },
  74748. enumerable: true,
  74749. configurable: true
  74750. });
  74751. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  74752. this._bodyUpdateRequired = false;
  74753. };
  74754. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  74755. if (this.object.getBoundingInfo) {
  74756. var q = this.object.rotationQuaternion;
  74757. //reset rotation
  74758. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  74759. //calculate the world matrix with no rotation
  74760. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  74761. var boundingInfo = this.object.getBoundingInfo();
  74762. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  74763. //bring back the rotation
  74764. this.object.rotationQuaternion = q;
  74765. //calculate the world matrix with the new rotation
  74766. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  74767. return size;
  74768. }
  74769. else {
  74770. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  74771. }
  74772. };
  74773. PhysicsImpostor.prototype.getObjectCenter = function () {
  74774. if (this.object.getBoundingInfo) {
  74775. var boundingInfo = this.object.getBoundingInfo();
  74776. return boundingInfo.boundingBox.centerWorld;
  74777. }
  74778. else {
  74779. return this.object.position;
  74780. }
  74781. };
  74782. /**
  74783. * Get a specific parametes from the options parameter.
  74784. */
  74785. PhysicsImpostor.prototype.getParam = function (paramName) {
  74786. return this._options[paramName];
  74787. };
  74788. /**
  74789. * Sets a specific parameter in the options given to the physics plugin
  74790. */
  74791. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  74792. this._options[paramName] = value;
  74793. this._bodyUpdateRequired = true;
  74794. };
  74795. /**
  74796. * Specifically change the body's mass option. Won't recreate the physics body object
  74797. */
  74798. PhysicsImpostor.prototype.setMass = function (mass) {
  74799. if (this.getParam("mass") !== mass) {
  74800. this.setParam("mass", mass);
  74801. }
  74802. if (this._physicsEngine) {
  74803. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  74804. }
  74805. };
  74806. PhysicsImpostor.prototype.getLinearVelocity = function () {
  74807. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  74808. };
  74809. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  74810. if (this._physicsEngine) {
  74811. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  74812. }
  74813. };
  74814. PhysicsImpostor.prototype.getAngularVelocity = function () {
  74815. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  74816. };
  74817. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  74818. if (this._physicsEngine) {
  74819. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  74820. }
  74821. };
  74822. /**
  74823. * Execute a function with the physics plugin native code.
  74824. * Provide a function the will have two variables - the world object and the physics body object.
  74825. */
  74826. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  74827. if (this._physicsEngine) {
  74828. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  74829. }
  74830. };
  74831. /**
  74832. * Register a function that will be executed before the physics world is stepping forward.
  74833. */
  74834. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  74835. this._onBeforePhysicsStepCallbacks.push(func);
  74836. };
  74837. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  74838. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  74839. if (index > -1) {
  74840. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  74841. }
  74842. else {
  74843. BABYLON.Tools.Warn("Function to remove was not found");
  74844. }
  74845. };
  74846. /**
  74847. * Register a function that will be executed after the physics step
  74848. */
  74849. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  74850. this._onAfterPhysicsStepCallbacks.push(func);
  74851. };
  74852. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  74853. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  74854. if (index > -1) {
  74855. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  74856. }
  74857. else {
  74858. BABYLON.Tools.Warn("Function to remove was not found");
  74859. }
  74860. };
  74861. /**
  74862. * register a function that will be executed when this impostor collides against a different body.
  74863. */
  74864. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  74865. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  74866. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  74867. };
  74868. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  74869. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  74870. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  74871. if (index > -1) {
  74872. this._onPhysicsCollideCallbacks.splice(index, 1);
  74873. }
  74874. else {
  74875. BABYLON.Tools.Warn("Function to remove was not found");
  74876. }
  74877. };
  74878. PhysicsImpostor.prototype.getParentsRotation = function () {
  74879. var parent = this.object.parent;
  74880. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  74881. while (parent) {
  74882. if (parent.rotationQuaternion) {
  74883. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  74884. }
  74885. else {
  74886. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  74887. }
  74888. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  74889. parent = parent.parent;
  74890. }
  74891. return this._tmpQuat;
  74892. };
  74893. /**
  74894. * Apply a force
  74895. */
  74896. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  74897. if (this._physicsEngine) {
  74898. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  74899. }
  74900. return this;
  74901. };
  74902. /**
  74903. * Apply an impulse
  74904. */
  74905. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  74906. if (this._physicsEngine) {
  74907. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  74908. }
  74909. return this;
  74910. };
  74911. /**
  74912. * A help function to create a joint.
  74913. */
  74914. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  74915. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  74916. this.addJoint(otherImpostor, joint);
  74917. return this;
  74918. };
  74919. /**
  74920. * Add a joint to this impostor with a different impostor.
  74921. */
  74922. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  74923. this._joints.push({
  74924. otherImpostor: otherImpostor,
  74925. joint: joint
  74926. });
  74927. if (this._physicsEngine) {
  74928. this._physicsEngine.addJoint(this, otherImpostor, joint);
  74929. }
  74930. return this;
  74931. };
  74932. /**
  74933. * Will keep this body still, in a sleep mode.
  74934. */
  74935. PhysicsImpostor.prototype.sleep = function () {
  74936. if (this._physicsEngine) {
  74937. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  74938. }
  74939. return this;
  74940. };
  74941. /**
  74942. * Wake the body up.
  74943. */
  74944. PhysicsImpostor.prototype.wakeUp = function () {
  74945. if (this._physicsEngine) {
  74946. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  74947. }
  74948. return this;
  74949. };
  74950. PhysicsImpostor.prototype.clone = function (newObject) {
  74951. if (!newObject)
  74952. return null;
  74953. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  74954. };
  74955. PhysicsImpostor.prototype.dispose = function () {
  74956. var _this = this;
  74957. //no dispose if no physics engine is available.
  74958. if (!this._physicsEngine) {
  74959. return;
  74960. }
  74961. this._joints.forEach(function (j) {
  74962. if (_this._physicsEngine) {
  74963. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  74964. }
  74965. });
  74966. //dispose the physics body
  74967. this._physicsEngine.removeImpostor(this);
  74968. if (this.parent) {
  74969. this.parent.forceUpdate();
  74970. }
  74971. else {
  74972. /*this._object.getChildMeshes().forEach(function(mesh) {
  74973. if (mesh.physicsImpostor) {
  74974. if (disposeChildren) {
  74975. mesh.physicsImpostor.dispose();
  74976. mesh.physicsImpostor = null;
  74977. }
  74978. }
  74979. })*/
  74980. }
  74981. this._isDisposed = true;
  74982. };
  74983. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  74984. this._deltaPosition.copyFrom(position);
  74985. };
  74986. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  74987. if (!this._deltaRotation) {
  74988. this._deltaRotation = new BABYLON.Quaternion();
  74989. }
  74990. this._deltaRotation.copyFrom(rotation);
  74991. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  74992. };
  74993. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  74994. if (this._physicsEngine) {
  74995. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  74996. }
  74997. return this;
  74998. };
  74999. PhysicsImpostor.prototype.getRadius = function () {
  75000. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  75001. };
  75002. /**
  75003. * Sync a bone with this impostor
  75004. * @param bone The bone to sync to the impostor.
  75005. * @param boneMesh The mesh that the bone is influencing.
  75006. * @param jointPivot The pivot of the joint / bone in local space.
  75007. * @param distToJoint Optional distance from the impostor to the joint.
  75008. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75009. */
  75010. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  75011. var tempVec = PhysicsImpostor._tmpVecs[0];
  75012. var mesh = this.object;
  75013. if (mesh.rotationQuaternion) {
  75014. if (adjustRotation) {
  75015. var tempQuat = PhysicsImpostor._tmpQuat;
  75016. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  75017. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  75018. }
  75019. else {
  75020. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  75021. }
  75022. }
  75023. tempVec.x = 0;
  75024. tempVec.y = 0;
  75025. tempVec.z = 0;
  75026. if (jointPivot) {
  75027. tempVec.x = jointPivot.x;
  75028. tempVec.y = jointPivot.y;
  75029. tempVec.z = jointPivot.z;
  75030. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  75031. if (distToJoint === undefined || distToJoint === null) {
  75032. distToJoint = jointPivot.length();
  75033. }
  75034. tempVec.x *= distToJoint;
  75035. tempVec.y *= distToJoint;
  75036. tempVec.z *= distToJoint;
  75037. }
  75038. if (bone.getParent()) {
  75039. tempVec.addInPlace(mesh.getAbsolutePosition());
  75040. bone.setAbsolutePosition(tempVec, boneMesh);
  75041. }
  75042. else {
  75043. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  75044. boneMesh.position.x -= tempVec.x;
  75045. boneMesh.position.y -= tempVec.y;
  75046. boneMesh.position.z -= tempVec.z;
  75047. }
  75048. };
  75049. /**
  75050. * Sync impostor to a bone
  75051. * @param bone The bone that the impostor will be synced to.
  75052. * @param boneMesh The mesh that the bone is influencing.
  75053. * @param jointPivot The pivot of the joint / bone in local space.
  75054. * @param distToJoint Optional distance from the impostor to the joint.
  75055. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75056. * @param boneAxis Optional vector3 axis the bone is aligned with
  75057. */
  75058. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  75059. var mesh = this.object;
  75060. if (mesh.rotationQuaternion) {
  75061. if (adjustRotation) {
  75062. var tempQuat = PhysicsImpostor._tmpQuat;
  75063. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  75064. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  75065. }
  75066. else {
  75067. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  75068. }
  75069. }
  75070. var pos = PhysicsImpostor._tmpVecs[0];
  75071. var boneDir = PhysicsImpostor._tmpVecs[1];
  75072. if (!boneAxis) {
  75073. boneAxis = PhysicsImpostor._tmpVecs[2];
  75074. boneAxis.x = 0;
  75075. boneAxis.y = 1;
  75076. boneAxis.z = 0;
  75077. }
  75078. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  75079. bone.getAbsolutePositionToRef(boneMesh, pos);
  75080. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  75081. distToJoint = jointPivot.length();
  75082. }
  75083. if (distToJoint !== undefined && distToJoint !== null) {
  75084. pos.x += boneDir.x * distToJoint;
  75085. pos.y += boneDir.y * distToJoint;
  75086. pos.z += boneDir.z * distToJoint;
  75087. }
  75088. mesh.setAbsolutePosition(pos);
  75089. };
  75090. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  75091. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  75092. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75093. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  75094. //Impostor types
  75095. PhysicsImpostor.NoImpostor = 0;
  75096. PhysicsImpostor.SphereImpostor = 1;
  75097. PhysicsImpostor.BoxImpostor = 2;
  75098. PhysicsImpostor.PlaneImpostor = 3;
  75099. PhysicsImpostor.MeshImpostor = 4;
  75100. PhysicsImpostor.CylinderImpostor = 7;
  75101. PhysicsImpostor.ParticleImpostor = 8;
  75102. PhysicsImpostor.HeightmapImpostor = 9;
  75103. return PhysicsImpostor;
  75104. }());
  75105. BABYLON.PhysicsImpostor = PhysicsImpostor;
  75106. })(BABYLON || (BABYLON = {}));
  75107. //# sourceMappingURL=babylon.physicsImpostor.js.map
  75108. var BABYLON;
  75109. (function (BABYLON) {
  75110. var PhysicsEngine = /** @class */ (function () {
  75111. function PhysicsEngine(gravity, _physicsPlugin) {
  75112. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  75113. this._physicsPlugin = _physicsPlugin;
  75114. //new methods and parameters
  75115. this._impostors = [];
  75116. this._joints = [];
  75117. if (!this._physicsPlugin.isSupported()) {
  75118. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  75119. + "Please make sure it is included.");
  75120. }
  75121. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  75122. this.setGravity(gravity);
  75123. this.setTimeStep();
  75124. }
  75125. PhysicsEngine.prototype.setGravity = function (gravity) {
  75126. this.gravity = gravity;
  75127. this._physicsPlugin.setGravity(this.gravity);
  75128. };
  75129. /**
  75130. * Set the time step of the physics engine.
  75131. * default is 1/60.
  75132. * To slow it down, enter 1/600 for example.
  75133. * To speed it up, 1/30
  75134. * @param {number} newTimeStep the new timestep to apply to this world.
  75135. */
  75136. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  75137. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  75138. this._physicsPlugin.setTimeStep(newTimeStep);
  75139. };
  75140. /**
  75141. * Get the time step of the physics engine.
  75142. */
  75143. PhysicsEngine.prototype.getTimeStep = function () {
  75144. return this._physicsPlugin.getTimeStep();
  75145. };
  75146. PhysicsEngine.prototype.dispose = function () {
  75147. this._impostors.forEach(function (impostor) {
  75148. impostor.dispose();
  75149. });
  75150. this._physicsPlugin.dispose();
  75151. };
  75152. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  75153. return this._physicsPlugin.name;
  75154. };
  75155. /**
  75156. * Adding a new impostor for the impostor tracking.
  75157. * This will be done by the impostor itself.
  75158. * @param {PhysicsImpostor} impostor the impostor to add
  75159. */
  75160. PhysicsEngine.prototype.addImpostor = function (impostor) {
  75161. impostor.uniqueId = this._impostors.push(impostor);
  75162. //if no parent, generate the body
  75163. if (!impostor.parent) {
  75164. this._physicsPlugin.generatePhysicsBody(impostor);
  75165. }
  75166. };
  75167. /**
  75168. * Remove an impostor from the engine.
  75169. * This impostor and its mesh will not longer be updated by the physics engine.
  75170. * @param {PhysicsImpostor} impostor the impostor to remove
  75171. */
  75172. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  75173. var index = this._impostors.indexOf(impostor);
  75174. if (index > -1) {
  75175. var removed = this._impostors.splice(index, 1);
  75176. //Is it needed?
  75177. if (removed.length) {
  75178. //this will also remove it from the world.
  75179. removed[0].physicsBody = null;
  75180. }
  75181. }
  75182. };
  75183. /**
  75184. * Add a joint to the physics engine
  75185. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  75186. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  75187. * @param {PhysicsJoint} the joint that will connect both impostors.
  75188. */
  75189. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  75190. var impostorJoint = {
  75191. mainImpostor: mainImpostor,
  75192. connectedImpostor: connectedImpostor,
  75193. joint: joint
  75194. };
  75195. joint.physicsPlugin = this._physicsPlugin;
  75196. this._joints.push(impostorJoint);
  75197. this._physicsPlugin.generateJoint(impostorJoint);
  75198. };
  75199. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  75200. var matchingJoints = this._joints.filter(function (impostorJoint) {
  75201. return (impostorJoint.connectedImpostor === connectedImpostor
  75202. && impostorJoint.joint === joint
  75203. && impostorJoint.mainImpostor === mainImpostor);
  75204. });
  75205. if (matchingJoints.length) {
  75206. this._physicsPlugin.removeJoint(matchingJoints[0]);
  75207. //TODO remove it from the list as well
  75208. }
  75209. };
  75210. /**
  75211. * Called by the scene. no need to call it.
  75212. */
  75213. PhysicsEngine.prototype._step = function (delta) {
  75214. var _this = this;
  75215. //check if any mesh has no body / requires an update
  75216. this._impostors.forEach(function (impostor) {
  75217. if (impostor.isBodyInitRequired()) {
  75218. _this._physicsPlugin.generatePhysicsBody(impostor);
  75219. }
  75220. });
  75221. if (delta > 0.1) {
  75222. delta = 0.1;
  75223. }
  75224. else if (delta <= 0) {
  75225. delta = 1.0 / 60.0;
  75226. }
  75227. this._physicsPlugin.executeStep(delta, this._impostors);
  75228. };
  75229. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  75230. return this._physicsPlugin;
  75231. };
  75232. PhysicsEngine.prototype.getImpostors = function () {
  75233. return this._impostors;
  75234. };
  75235. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  75236. for (var i = 0; i < this._impostors.length; ++i) {
  75237. if (this._impostors[i].object === object) {
  75238. return this._impostors[i];
  75239. }
  75240. }
  75241. return null;
  75242. };
  75243. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  75244. for (var i = 0; i < this._impostors.length; ++i) {
  75245. if (this._impostors[i].physicsBody === body) {
  75246. return this._impostors[i];
  75247. }
  75248. }
  75249. return null;
  75250. };
  75251. // Statics
  75252. PhysicsEngine.Epsilon = 0.001;
  75253. return PhysicsEngine;
  75254. }());
  75255. BABYLON.PhysicsEngine = PhysicsEngine;
  75256. })(BABYLON || (BABYLON = {}));
  75257. //# sourceMappingURL=babylon.physicsEngine.js.map
  75258. var BABYLON;
  75259. (function (BABYLON) {
  75260. var PhysicsHelper = /** @class */ (function () {
  75261. function PhysicsHelper(scene) {
  75262. this._scene = scene;
  75263. this._physicsEngine = this._scene.getPhysicsEngine();
  75264. if (!this._physicsEngine) {
  75265. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  75266. }
  75267. }
  75268. /**
  75269. * @param {Vector3} origin the origin of the explosion
  75270. * @param {number} radius the explosion radius
  75271. * @param {number} strength the explosion strength
  75272. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75273. */
  75274. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  75275. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75276. if (!this._physicsEngine) {
  75277. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  75278. return null;
  75279. }
  75280. var impostors = this._physicsEngine.getImpostors();
  75281. if (impostors.length === 0) {
  75282. return null;
  75283. }
  75284. var event = new PhysicsRadialExplosionEvent(this._scene);
  75285. impostors.forEach(function (impostor) {
  75286. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75287. if (!impostorForceAndContactPoint) {
  75288. return;
  75289. }
  75290. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75291. });
  75292. event.dispose(false);
  75293. return event;
  75294. };
  75295. /**
  75296. * @param {Vector3} origin the origin of the explosion
  75297. * @param {number} radius the explosion radius
  75298. * @param {number} strength the explosion strength
  75299. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75300. */
  75301. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  75302. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75303. if (!this._physicsEngine) {
  75304. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75305. return null;
  75306. }
  75307. var impostors = this._physicsEngine.getImpostors();
  75308. if (impostors.length === 0) {
  75309. return null;
  75310. }
  75311. var event = new PhysicsRadialExplosionEvent(this._scene);
  75312. impostors.forEach(function (impostor) {
  75313. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75314. if (!impostorForceAndContactPoint) {
  75315. return;
  75316. }
  75317. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75318. });
  75319. event.dispose(false);
  75320. return event;
  75321. };
  75322. /**
  75323. * @param {Vector3} origin the origin of the explosion
  75324. * @param {number} radius the explosion radius
  75325. * @param {number} strength the explosion strength
  75326. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75327. */
  75328. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  75329. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75330. if (!this._physicsEngine) {
  75331. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75332. return null;
  75333. }
  75334. var impostors = this._physicsEngine.getImpostors();
  75335. if (impostors.length === 0) {
  75336. return null;
  75337. }
  75338. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  75339. event.dispose(false);
  75340. return event;
  75341. };
  75342. /**
  75343. * @param {Vector3} origin the origin of the updraft
  75344. * @param {number} radius the radius of the updraft
  75345. * @param {number} strength the strength of the updraft
  75346. * @param {number} height the height of the updraft
  75347. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  75348. */
  75349. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  75350. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  75351. if (!this._physicsEngine) {
  75352. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75353. return null;
  75354. }
  75355. if (this._physicsEngine.getImpostors().length === 0) {
  75356. return null;
  75357. }
  75358. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  75359. event.dispose(false);
  75360. return event;
  75361. };
  75362. /**
  75363. * @param {Vector3} origin the of the vortex
  75364. * @param {number} radius the radius of the vortex
  75365. * @param {number} strength the strength of the vortex
  75366. * @param {number} height the height of the vortex
  75367. */
  75368. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  75369. if (!this._physicsEngine) {
  75370. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75371. return null;
  75372. }
  75373. if (this._physicsEngine.getImpostors().length === 0) {
  75374. return null;
  75375. }
  75376. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  75377. event.dispose(false);
  75378. return event;
  75379. };
  75380. return PhysicsHelper;
  75381. }());
  75382. BABYLON.PhysicsHelper = PhysicsHelper;
  75383. /***** Radial explosion *****/
  75384. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  75385. function PhysicsRadialExplosionEvent(scene) {
  75386. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  75387. this._rays = [];
  75388. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  75389. this._scene = scene;
  75390. }
  75391. /**
  75392. * Returns the data related to the radial explosion event (sphere & rays).
  75393. * @returns {PhysicsRadialExplosionEventData}
  75394. */
  75395. PhysicsRadialExplosionEvent.prototype.getData = function () {
  75396. this._dataFetched = true;
  75397. return {
  75398. sphere: this._sphere,
  75399. rays: this._rays,
  75400. };
  75401. };
  75402. /**
  75403. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  75404. * @param impostor
  75405. * @param {Vector3} origin the origin of the explosion
  75406. * @param {number} radius the explosion radius
  75407. * @param {number} strength the explosion strength
  75408. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  75409. * @returns {Nullable<PhysicsForceAndContactPoint>}
  75410. */
  75411. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  75412. if (impostor.mass === 0) {
  75413. return null;
  75414. }
  75415. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  75416. return null;
  75417. }
  75418. if (impostor.object.getClassName() !== 'Mesh') {
  75419. return null;
  75420. }
  75421. var impostorObject = impostor.object;
  75422. var impostorObjectCenter = impostor.getObjectCenter();
  75423. var direction = impostorObjectCenter.subtract(origin);
  75424. var ray = new BABYLON.Ray(origin, direction, radius);
  75425. this._rays.push(ray);
  75426. var hit = ray.intersectsMesh(impostorObject);
  75427. var contactPoint = hit.pickedPoint;
  75428. if (!contactPoint) {
  75429. return null;
  75430. }
  75431. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  75432. if (distanceFromOrigin > radius) {
  75433. return null;
  75434. }
  75435. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  75436. ? strength
  75437. : strength * (1 - (distanceFromOrigin / radius));
  75438. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75439. return { force: force, contactPoint: contactPoint };
  75440. };
  75441. /**
  75442. * Disposes the sphere.
  75443. * @param {bolean} force
  75444. */
  75445. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  75446. var _this = this;
  75447. if (force === void 0) { force = true; }
  75448. if (force) {
  75449. this._sphere.dispose();
  75450. }
  75451. else {
  75452. setTimeout(function () {
  75453. if (!_this._dataFetched) {
  75454. _this._sphere.dispose();
  75455. }
  75456. }, 0);
  75457. }
  75458. };
  75459. /*** Helpers ***/
  75460. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  75461. if (!this._sphere) {
  75462. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  75463. this._sphere.isVisible = false;
  75464. }
  75465. };
  75466. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  75467. var impostorObject = impostor.object;
  75468. this._prepareSphere();
  75469. this._sphere.position = origin;
  75470. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  75471. this._sphere._updateBoundingInfo();
  75472. this._sphere.computeWorldMatrix(true);
  75473. return this._sphere.intersectsMesh(impostorObject, true);
  75474. };
  75475. return PhysicsRadialExplosionEvent;
  75476. }());
  75477. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  75478. /***** Gravitational Field *****/
  75479. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  75480. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  75481. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75482. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75483. this._physicsHelper = physicsHelper;
  75484. this._scene = scene;
  75485. this._origin = origin;
  75486. this._radius = radius;
  75487. this._strength = strength;
  75488. this._falloff = falloff;
  75489. this._tickCallback = this._tick.bind(this);
  75490. }
  75491. /**
  75492. * Returns the data related to the gravitational field event (sphere).
  75493. * @returns {PhysicsGravitationalFieldEventData}
  75494. */
  75495. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  75496. this._dataFetched = true;
  75497. return {
  75498. sphere: this._sphere,
  75499. };
  75500. };
  75501. /**
  75502. * Enables the gravitational field.
  75503. */
  75504. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  75505. this._tickCallback.call(this);
  75506. this._scene.registerBeforeRender(this._tickCallback);
  75507. };
  75508. /**
  75509. * Disables the gravitational field.
  75510. */
  75511. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  75512. this._scene.unregisterBeforeRender(this._tickCallback);
  75513. };
  75514. /**
  75515. * Disposes the sphere.
  75516. * @param {bolean} force
  75517. */
  75518. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  75519. var _this = this;
  75520. if (force === void 0) { force = true; }
  75521. if (force) {
  75522. this._sphere.dispose();
  75523. }
  75524. else {
  75525. setTimeout(function () {
  75526. if (!_this._dataFetched) {
  75527. _this._sphere.dispose();
  75528. }
  75529. }, 0);
  75530. }
  75531. };
  75532. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  75533. // Since the params won't change, we fetch the event only once
  75534. if (this._sphere) {
  75535. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75536. }
  75537. else {
  75538. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75539. if (radialExplosionEvent) {
  75540. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  75541. }
  75542. }
  75543. };
  75544. return PhysicsGravitationalFieldEvent;
  75545. }());
  75546. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  75547. /***** Updraft *****/
  75548. var PhysicsUpdraftEvent = /** @class */ (function () {
  75549. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  75550. this._scene = _scene;
  75551. this._origin = _origin;
  75552. this._radius = _radius;
  75553. this._strength = _strength;
  75554. this._height = _height;
  75555. this._updraftMode = _updraftMode;
  75556. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  75557. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  75558. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  75559. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75560. this._physicsEngine = this._scene.getPhysicsEngine();
  75561. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  75562. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  75563. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  75564. this._originDirection = this._origin.subtract(this._originTop).normalize();
  75565. }
  75566. this._tickCallback = this._tick.bind(this);
  75567. }
  75568. /**
  75569. * Returns the data related to the updraft event (cylinder).
  75570. * @returns {PhysicsUpdraftEventData}
  75571. */
  75572. PhysicsUpdraftEvent.prototype.getData = function () {
  75573. this._dataFetched = true;
  75574. return {
  75575. cylinder: this._cylinder,
  75576. };
  75577. };
  75578. /**
  75579. * Enables the updraft.
  75580. */
  75581. PhysicsUpdraftEvent.prototype.enable = function () {
  75582. this._tickCallback.call(this);
  75583. this._scene.registerBeforeRender(this._tickCallback);
  75584. };
  75585. /**
  75586. * Disables the cortex.
  75587. */
  75588. PhysicsUpdraftEvent.prototype.disable = function () {
  75589. this._scene.unregisterBeforeRender(this._tickCallback);
  75590. };
  75591. /**
  75592. * Disposes the sphere.
  75593. * @param {bolean} force
  75594. */
  75595. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  75596. var _this = this;
  75597. if (force === void 0) { force = true; }
  75598. if (force) {
  75599. this._cylinder.dispose();
  75600. }
  75601. else {
  75602. setTimeout(function () {
  75603. if (!_this._dataFetched) {
  75604. _this._cylinder.dispose();
  75605. }
  75606. }, 0);
  75607. }
  75608. };
  75609. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75610. if (impostor.mass === 0) {
  75611. return null;
  75612. }
  75613. if (!this._intersectsWithCylinder(impostor)) {
  75614. return null;
  75615. }
  75616. var impostorObjectCenter = impostor.getObjectCenter();
  75617. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  75618. var direction = this._originDirection;
  75619. }
  75620. else {
  75621. var direction = impostorObjectCenter.subtract(this._originTop);
  75622. }
  75623. var multiplier = this._strength * -1;
  75624. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75625. return { force: force, contactPoint: impostorObjectCenter };
  75626. };
  75627. PhysicsUpdraftEvent.prototype._tick = function () {
  75628. var _this = this;
  75629. this._physicsEngine.getImpostors().forEach(function (impostor) {
  75630. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  75631. if (!impostorForceAndContactPoint) {
  75632. return;
  75633. }
  75634. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75635. });
  75636. };
  75637. /*** Helpers ***/
  75638. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  75639. if (!this._cylinder) {
  75640. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  75641. height: this._height,
  75642. diameter: this._radius * 2,
  75643. }, this._scene);
  75644. this._cylinder.isVisible = false;
  75645. }
  75646. };
  75647. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  75648. var impostorObject = impostor.object;
  75649. this._prepareCylinder();
  75650. this._cylinder.position = this._cylinderPosition;
  75651. return this._cylinder.intersectsMesh(impostorObject, true);
  75652. };
  75653. return PhysicsUpdraftEvent;
  75654. }());
  75655. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  75656. /***** Vortex *****/
  75657. var PhysicsVortexEvent = /** @class */ (function () {
  75658. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  75659. this._scene = _scene;
  75660. this._origin = _origin;
  75661. this._radius = _radius;
  75662. this._strength = _strength;
  75663. this._height = _height;
  75664. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  75665. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  75666. this._updraftMultiplier = 0.02;
  75667. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  75668. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75669. this._physicsEngine = this._scene.getPhysicsEngine();
  75670. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  75671. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  75672. this._tickCallback = this._tick.bind(this);
  75673. }
  75674. /**
  75675. * Returns the data related to the vortex event (cylinder).
  75676. * @returns {PhysicsVortexEventData}
  75677. */
  75678. PhysicsVortexEvent.prototype.getData = function () {
  75679. this._dataFetched = true;
  75680. return {
  75681. cylinder: this._cylinder,
  75682. };
  75683. };
  75684. /**
  75685. * Enables the vortex.
  75686. */
  75687. PhysicsVortexEvent.prototype.enable = function () {
  75688. this._tickCallback.call(this);
  75689. this._scene.registerBeforeRender(this._tickCallback);
  75690. };
  75691. /**
  75692. * Disables the cortex.
  75693. */
  75694. PhysicsVortexEvent.prototype.disable = function () {
  75695. this._scene.unregisterBeforeRender(this._tickCallback);
  75696. };
  75697. /**
  75698. * Disposes the sphere.
  75699. * @param {bolean} force
  75700. */
  75701. PhysicsVortexEvent.prototype.dispose = function (force) {
  75702. var _this = this;
  75703. if (force === void 0) { force = true; }
  75704. if (force) {
  75705. this._cylinder.dispose();
  75706. }
  75707. else {
  75708. setTimeout(function () {
  75709. if (!_this._dataFetched) {
  75710. _this._cylinder.dispose();
  75711. }
  75712. }, 0);
  75713. }
  75714. };
  75715. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75716. if (impostor.mass === 0) {
  75717. return null;
  75718. }
  75719. if (!this._intersectsWithCylinder(impostor)) {
  75720. return null;
  75721. }
  75722. if (impostor.object.getClassName() !== 'Mesh') {
  75723. return null;
  75724. }
  75725. var impostorObject = impostor.object;
  75726. var impostorObjectCenter = impostor.getObjectCenter();
  75727. 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)
  75728. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  75729. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  75730. var hit = ray.intersectsMesh(impostorObject);
  75731. var contactPoint = hit.pickedPoint;
  75732. if (!contactPoint) {
  75733. return null;
  75734. }
  75735. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  75736. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  75737. var directionToOrigin = contactPoint.normalize();
  75738. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  75739. directionToOrigin = directionToOrigin.negate();
  75740. }
  75741. // TODO: find a more physically based solution
  75742. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  75743. var forceX = directionToOrigin.x * this._strength / 8;
  75744. var forceY = directionToOrigin.y * this._updraftMultiplier;
  75745. var forceZ = directionToOrigin.z * this._strength / 8;
  75746. }
  75747. else {
  75748. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  75749. var forceY = this._originTop.y * this._updraftMultiplier;
  75750. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  75751. }
  75752. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  75753. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  75754. return { force: force, contactPoint: impostorObjectCenter };
  75755. };
  75756. PhysicsVortexEvent.prototype._tick = function () {
  75757. var _this = this;
  75758. this._physicsEngine.getImpostors().forEach(function (impostor) {
  75759. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  75760. if (!impostorForceAndContactPoint) {
  75761. return;
  75762. }
  75763. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75764. });
  75765. };
  75766. /*** Helpers ***/
  75767. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  75768. if (!this._cylinder) {
  75769. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  75770. height: this._height,
  75771. diameter: this._radius * 2,
  75772. }, this._scene);
  75773. this._cylinder.isVisible = false;
  75774. }
  75775. };
  75776. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  75777. var impostorObject = impostor.object;
  75778. this._prepareCylinder();
  75779. this._cylinder.position = this._cylinderPosition;
  75780. return this._cylinder.intersectsMesh(impostorObject, true);
  75781. };
  75782. return PhysicsVortexEvent;
  75783. }());
  75784. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  75785. /***** Enums *****/
  75786. /**
  75787. * The strenght of the force in correspondence to the distance of the affected object
  75788. */
  75789. var PhysicsRadialImpulseFalloff;
  75790. (function (PhysicsRadialImpulseFalloff) {
  75791. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  75792. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  75793. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  75794. /**
  75795. * The strenght of the force in correspondence to the distance of the affected object
  75796. */
  75797. var PhysicsUpdraftMode;
  75798. (function (PhysicsUpdraftMode) {
  75799. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  75800. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  75801. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  75802. })(BABYLON || (BABYLON = {}));
  75803. //# sourceMappingURL=babylon.physicsHelper.js.map
  75804. var BABYLON;
  75805. (function (BABYLON) {
  75806. var CannonJSPlugin = /** @class */ (function () {
  75807. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  75808. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  75809. if (iterations === void 0) { iterations = 10; }
  75810. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  75811. this.name = "CannonJSPlugin";
  75812. this._physicsMaterials = new Array();
  75813. this._fixedTimeStep = 1 / 60;
  75814. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  75815. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  75816. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  75817. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  75818. this._tmpPosition = BABYLON.Vector3.Zero();
  75819. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  75820. this._tmpUnityRotation = new BABYLON.Quaternion();
  75821. if (!this.isSupported()) {
  75822. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  75823. return;
  75824. }
  75825. this._extendNamespace();
  75826. this.world = new this.BJSCANNON.World();
  75827. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  75828. this.world.solver.iterations = iterations;
  75829. }
  75830. CannonJSPlugin.prototype.setGravity = function (gravity) {
  75831. this.world.gravity.copy(gravity);
  75832. };
  75833. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  75834. this._fixedTimeStep = timeStep;
  75835. };
  75836. CannonJSPlugin.prototype.getTimeStep = function () {
  75837. return this._fixedTimeStep;
  75838. };
  75839. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  75840. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  75841. };
  75842. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  75843. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  75844. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  75845. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  75846. };
  75847. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  75848. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  75849. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  75850. impostor.physicsBody.applyForce(impulse, worldPoint);
  75851. };
  75852. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  75853. //parent-child relationship. Does this impostor has a parent impostor?
  75854. if (impostor.parent) {
  75855. if (impostor.physicsBody) {
  75856. this.removePhysicsBody(impostor);
  75857. //TODO is that needed?
  75858. impostor.forceUpdate();
  75859. }
  75860. return;
  75861. }
  75862. //should a new body be created for this impostor?
  75863. if (impostor.isBodyInitRequired()) {
  75864. var shape = this._createShape(impostor);
  75865. //unregister events, if body is being changed
  75866. var oldBody = impostor.physicsBody;
  75867. if (oldBody) {
  75868. this.removePhysicsBody(impostor);
  75869. }
  75870. //create the body and material
  75871. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  75872. var bodyCreationObject = {
  75873. mass: impostor.getParam("mass"),
  75874. material: material
  75875. };
  75876. // A simple extend, in case native options were used.
  75877. var nativeOptions = impostor.getParam("nativeOptions");
  75878. for (var key in nativeOptions) {
  75879. if (nativeOptions.hasOwnProperty(key)) {
  75880. bodyCreationObject[key] = nativeOptions[key];
  75881. }
  75882. }
  75883. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  75884. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  75885. this.world.addEventListener("preStep", impostor.beforeStep);
  75886. this.world.addEventListener("postStep", impostor.afterStep);
  75887. impostor.physicsBody.addShape(shape);
  75888. this.world.add(impostor.physicsBody);
  75889. //try to keep the body moving in the right direction by taking old properties.
  75890. //Should be tested!
  75891. if (oldBody) {
  75892. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  75893. impostor.physicsBody[param].copy(oldBody[param]);
  75894. });
  75895. }
  75896. this._processChildMeshes(impostor);
  75897. }
  75898. //now update the body's transformation
  75899. this._updatePhysicsBodyTransformation(impostor);
  75900. };
  75901. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  75902. var _this = this;
  75903. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  75904. var currentRotation = mainImpostor.object.rotationQuaternion;
  75905. if (meshChildren.length) {
  75906. var processMesh = function (localPosition, mesh) {
  75907. if (!currentRotation || !mesh.rotationQuaternion) {
  75908. return;
  75909. }
  75910. var childImpostor = mesh.getPhysicsImpostor();
  75911. if (childImpostor) {
  75912. var parent = childImpostor.parent;
  75913. if (parent !== mainImpostor) {
  75914. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  75915. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  75916. if (childImpostor.physicsBody) {
  75917. _this.removePhysicsBody(childImpostor);
  75918. childImpostor.physicsBody = null;
  75919. }
  75920. childImpostor.parent = mainImpostor;
  75921. childImpostor.resetUpdateFlags();
  75922. 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));
  75923. //Add the mass of the children.
  75924. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  75925. }
  75926. }
  75927. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  75928. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  75929. };
  75930. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  75931. }
  75932. };
  75933. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75934. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  75935. this.world.removeEventListener("preStep", impostor.beforeStep);
  75936. this.world.removeEventListener("postStep", impostor.afterStep);
  75937. this.world.remove(impostor.physicsBody);
  75938. };
  75939. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75940. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75941. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75942. if (!mainBody || !connectedBody) {
  75943. return;
  75944. }
  75945. var constraint;
  75946. var jointData = impostorJoint.joint.jointData;
  75947. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  75948. var constraintData = {
  75949. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  75950. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  75951. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  75952. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  75953. maxForce: jointData.nativeParams.maxForce,
  75954. collideConnected: !!jointData.collision
  75955. };
  75956. switch (impostorJoint.joint.type) {
  75957. case BABYLON.PhysicsJoint.HingeJoint:
  75958. case BABYLON.PhysicsJoint.Hinge2Joint:
  75959. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  75960. break;
  75961. case BABYLON.PhysicsJoint.DistanceJoint:
  75962. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  75963. break;
  75964. case BABYLON.PhysicsJoint.SpringJoint:
  75965. var springData = jointData;
  75966. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  75967. restLength: springData.length,
  75968. stiffness: springData.stiffness,
  75969. damping: springData.damping,
  75970. localAnchorA: constraintData.pivotA,
  75971. localAnchorB: constraintData.pivotB
  75972. });
  75973. break;
  75974. case BABYLON.PhysicsJoint.LockJoint:
  75975. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  75976. break;
  75977. case BABYLON.PhysicsJoint.PointToPointJoint:
  75978. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  75979. default:
  75980. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  75981. break;
  75982. }
  75983. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  75984. constraint.collideConnected = !!jointData.collision;
  75985. impostorJoint.joint.physicsJoint = constraint;
  75986. //don't add spring as constraint, as it is not one.
  75987. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  75988. this.world.addConstraint(constraint);
  75989. }
  75990. else {
  75991. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  75992. constraint.applyForce();
  75993. });
  75994. }
  75995. };
  75996. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  75997. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  75998. };
  75999. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  76000. var index;
  76001. var mat;
  76002. for (index = 0; index < this._physicsMaterials.length; index++) {
  76003. mat = this._physicsMaterials[index];
  76004. if (mat.friction === friction && mat.restitution === restitution) {
  76005. return mat;
  76006. }
  76007. }
  76008. var currentMat = new this.BJSCANNON.Material(name);
  76009. currentMat.friction = friction;
  76010. currentMat.restitution = restitution;
  76011. this._physicsMaterials.push(currentMat);
  76012. return currentMat;
  76013. };
  76014. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  76015. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  76016. };
  76017. CannonJSPlugin.prototype._createShape = function (impostor) {
  76018. var object = impostor.object;
  76019. var returnValue;
  76020. var extendSize = impostor.getObjectExtendSize();
  76021. switch (impostor.type) {
  76022. case BABYLON.PhysicsImpostor.SphereImpostor:
  76023. var radiusX = extendSize.x;
  76024. var radiusY = extendSize.y;
  76025. var radiusZ = extendSize.z;
  76026. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  76027. break;
  76028. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  76029. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76030. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  76031. break;
  76032. case BABYLON.PhysicsImpostor.BoxImpostor:
  76033. var box = extendSize.scale(0.5);
  76034. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  76035. break;
  76036. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76037. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  76038. returnValue = new this.BJSCANNON.Plane();
  76039. break;
  76040. case BABYLON.PhysicsImpostor.MeshImpostor:
  76041. // should transform the vertex data to world coordinates!!
  76042. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  76043. var rawFaces = object.getIndices ? object.getIndices() : [];
  76044. if (!rawVerts)
  76045. return;
  76046. // get only scale! so the object could transform correctly.
  76047. var oldPosition = object.position.clone();
  76048. var oldRotation = object.rotation && object.rotation.clone();
  76049. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  76050. object.position.copyFromFloats(0, 0, 0);
  76051. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76052. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76053. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76054. var transform = object.computeWorldMatrix(true);
  76055. // convert rawVerts to object space
  76056. var temp = new Array();
  76057. var index;
  76058. for (index = 0; index < rawVerts.length; index += 3) {
  76059. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  76060. }
  76061. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  76062. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  76063. //now set back the transformation!
  76064. object.position.copyFrom(oldPosition);
  76065. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  76066. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  76067. break;
  76068. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  76069. var oldPosition2 = object.position.clone();
  76070. var oldRotation2 = object.rotation && object.rotation.clone();
  76071. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  76072. object.position.copyFromFloats(0, 0, 0);
  76073. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76074. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76075. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76076. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  76077. returnValue = this._createHeightmap(object);
  76078. object.position.copyFrom(oldPosition2);
  76079. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  76080. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  76081. object.computeWorldMatrix(true);
  76082. break;
  76083. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76084. returnValue = new this.BJSCANNON.Particle();
  76085. break;
  76086. }
  76087. return returnValue;
  76088. };
  76089. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  76090. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76091. var transform = object.computeWorldMatrix(true);
  76092. // convert rawVerts to object space
  76093. var temp = new Array();
  76094. var index;
  76095. for (index = 0; index < pos.length; index += 3) {
  76096. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  76097. }
  76098. pos = temp;
  76099. var matrix = new Array();
  76100. //For now pointDepth will not be used and will be automatically calculated.
  76101. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  76102. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  76103. var boundingInfo = object.getBoundingInfo();
  76104. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  76105. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  76106. var elementSize = dim * 2 / arraySize;
  76107. for (var i = 0; i < pos.length; i = i + 3) {
  76108. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  76109. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  76110. var y = -pos[i + 2] + minY;
  76111. if (!matrix[x]) {
  76112. matrix[x] = [];
  76113. }
  76114. if (!matrix[x][z]) {
  76115. matrix[x][z] = y;
  76116. }
  76117. matrix[x][z] = Math.max(y, matrix[x][z]);
  76118. }
  76119. for (var x = 0; x <= arraySize; ++x) {
  76120. if (!matrix[x]) {
  76121. var loc = 1;
  76122. while (!matrix[(x + loc) % arraySize]) {
  76123. loc++;
  76124. }
  76125. matrix[x] = matrix[(x + loc) % arraySize].slice();
  76126. //console.log("missing x", x);
  76127. }
  76128. for (var z = 0; z <= arraySize; ++z) {
  76129. if (!matrix[x][z]) {
  76130. var loc = 1;
  76131. var newValue;
  76132. while (newValue === undefined) {
  76133. newValue = matrix[x][(z + loc++) % arraySize];
  76134. }
  76135. matrix[x][z] = newValue;
  76136. }
  76137. }
  76138. }
  76139. var shape = new this.BJSCANNON.Heightfield(matrix, {
  76140. elementSize: elementSize
  76141. });
  76142. //For future reference, needed for body transformation
  76143. shape.minY = minY;
  76144. return shape;
  76145. };
  76146. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  76147. var object = impostor.object;
  76148. //make sure it is updated...
  76149. object.computeWorldMatrix && object.computeWorldMatrix(true);
  76150. // The delta between the mesh position and the mesh bounding box center
  76151. var bInfo = object.getBoundingInfo();
  76152. if (!bInfo)
  76153. return;
  76154. var center = impostor.getObjectCenter();
  76155. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  76156. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  76157. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  76158. this._tmpPosition.copyFrom(center);
  76159. var quaternion = object.rotationQuaternion;
  76160. if (!quaternion) {
  76161. return;
  76162. }
  76163. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  76164. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  76165. //-90 DEG in X, precalculated
  76166. quaternion = quaternion.multiply(this._minus90X);
  76167. //Invert! (Precalculated, 90 deg in X)
  76168. //No need to clone. this will never change.
  76169. impostor.setDeltaRotation(this._plus90X);
  76170. }
  76171. //If it is a heightfield, if should be centered.
  76172. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  76173. var mesh = object;
  76174. var boundingInfo = mesh.getBoundingInfo();
  76175. //calculate the correct body position:
  76176. var rotationQuaternion = mesh.rotationQuaternion;
  76177. mesh.rotationQuaternion = this._tmpUnityRotation;
  76178. mesh.computeWorldMatrix(true);
  76179. //get original center with no rotation
  76180. var c = center.clone();
  76181. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  76182. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  76183. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  76184. mesh.setPreTransformMatrix(p);
  76185. mesh.computeWorldMatrix(true);
  76186. //calculate the translation
  76187. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  76188. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  76189. //add it inverted to the delta
  76190. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  76191. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  76192. //rotation is back
  76193. mesh.rotationQuaternion = rotationQuaternion;
  76194. mesh.setPreTransformMatrix(oldPivot);
  76195. mesh.computeWorldMatrix(true);
  76196. }
  76197. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  76198. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  76199. //this._tmpPosition.copyFrom(object.position);
  76200. }
  76201. impostor.setDeltaPosition(this._tmpDeltaPosition);
  76202. //Now update the impostor object
  76203. impostor.physicsBody.position.copy(this._tmpPosition);
  76204. impostor.physicsBody.quaternion.copy(quaternion);
  76205. };
  76206. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76207. impostor.object.position.copyFrom(impostor.physicsBody.position);
  76208. if (impostor.object.rotationQuaternion) {
  76209. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  76210. }
  76211. };
  76212. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76213. impostor.physicsBody.position.copy(newPosition);
  76214. impostor.physicsBody.quaternion.copy(newRotation);
  76215. };
  76216. CannonJSPlugin.prototype.isSupported = function () {
  76217. return this.BJSCANNON !== undefined;
  76218. };
  76219. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76220. impostor.physicsBody.velocity.copy(velocity);
  76221. };
  76222. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76223. impostor.physicsBody.angularVelocity.copy(velocity);
  76224. };
  76225. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76226. var v = impostor.physicsBody.velocity;
  76227. if (!v) {
  76228. return null;
  76229. }
  76230. return new BABYLON.Vector3(v.x, v.y, v.z);
  76231. };
  76232. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76233. var v = impostor.physicsBody.angularVelocity;
  76234. if (!v) {
  76235. return null;
  76236. }
  76237. return new BABYLON.Vector3(v.x, v.y, v.z);
  76238. };
  76239. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76240. impostor.physicsBody.mass = mass;
  76241. impostor.physicsBody.updateMassProperties();
  76242. };
  76243. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  76244. return impostor.physicsBody.mass;
  76245. };
  76246. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  76247. return impostor.physicsBody.material.friction;
  76248. };
  76249. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76250. impostor.physicsBody.material.friction = friction;
  76251. };
  76252. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76253. return impostor.physicsBody.material.restitution;
  76254. };
  76255. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76256. impostor.physicsBody.material.restitution = restitution;
  76257. };
  76258. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  76259. impostor.physicsBody.sleep();
  76260. };
  76261. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  76262. impostor.physicsBody.wakeUp();
  76263. };
  76264. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76265. joint.physicsJoint.distance = maxDistance;
  76266. };
  76267. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76268. // if (!motorIndex) {
  76269. // joint.physicsJoint.enableMotor();
  76270. // }
  76271. // }
  76272. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76273. // if (!motorIndex) {
  76274. // joint.physicsJoint.disableMotor();
  76275. // }
  76276. // }
  76277. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76278. if (!motorIndex) {
  76279. joint.physicsJoint.enableMotor();
  76280. joint.physicsJoint.setMotorSpeed(speed);
  76281. if (maxForce) {
  76282. this.setLimit(joint, maxForce);
  76283. }
  76284. }
  76285. };
  76286. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  76287. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  76288. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  76289. };
  76290. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76291. var body = impostor.physicsBody;
  76292. mesh.position.x = body.position.x;
  76293. mesh.position.y = body.position.y;
  76294. mesh.position.z = body.position.z;
  76295. if (mesh.rotationQuaternion) {
  76296. mesh.rotationQuaternion.x = body.quaternion.x;
  76297. mesh.rotationQuaternion.y = body.quaternion.y;
  76298. mesh.rotationQuaternion.z = body.quaternion.z;
  76299. mesh.rotationQuaternion.w = body.quaternion.w;
  76300. }
  76301. };
  76302. CannonJSPlugin.prototype.getRadius = function (impostor) {
  76303. var shape = impostor.physicsBody.shapes[0];
  76304. return shape.boundingSphereRadius;
  76305. };
  76306. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76307. var shape = impostor.physicsBody.shapes[0];
  76308. result.x = shape.halfExtents.x * 2;
  76309. result.y = shape.halfExtents.y * 2;
  76310. result.z = shape.halfExtents.z * 2;
  76311. };
  76312. CannonJSPlugin.prototype.dispose = function () {
  76313. };
  76314. CannonJSPlugin.prototype._extendNamespace = function () {
  76315. //this will force cannon to execute at least one step when using interpolation
  76316. var step_tmp1 = new this.BJSCANNON.Vec3();
  76317. var Engine = this.BJSCANNON;
  76318. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  76319. maxSubSteps = maxSubSteps || 10;
  76320. timeSinceLastCalled = timeSinceLastCalled || 0;
  76321. if (timeSinceLastCalled === 0) {
  76322. this.internalStep(dt);
  76323. this.time += dt;
  76324. }
  76325. else {
  76326. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  76327. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  76328. var t0 = performance.now();
  76329. for (var i = 0; i !== internalSteps; i++) {
  76330. this.internalStep(dt);
  76331. if (performance.now() - t0 > dt * 1000) {
  76332. break;
  76333. }
  76334. }
  76335. this.time += timeSinceLastCalled;
  76336. var h = this.time % dt;
  76337. var h_div_dt = h / dt;
  76338. var interpvelo = step_tmp1;
  76339. var bodies = this.bodies;
  76340. for (var j = 0; j !== bodies.length; j++) {
  76341. var b = bodies[j];
  76342. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  76343. b.position.vsub(b.previousPosition, interpvelo);
  76344. interpvelo.scale(h_div_dt, interpvelo);
  76345. b.position.vadd(interpvelo, b.interpolatedPosition);
  76346. }
  76347. else {
  76348. b.interpolatedPosition.copy(b.position);
  76349. b.interpolatedQuaternion.copy(b.quaternion);
  76350. }
  76351. }
  76352. }
  76353. };
  76354. };
  76355. return CannonJSPlugin;
  76356. }());
  76357. BABYLON.CannonJSPlugin = CannonJSPlugin;
  76358. })(BABYLON || (BABYLON = {}));
  76359. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  76360. var BABYLON;
  76361. (function (BABYLON) {
  76362. var OimoJSPlugin = /** @class */ (function () {
  76363. function OimoJSPlugin(iterations) {
  76364. this.name = "OimoJSPlugin";
  76365. this._tmpImpostorsArray = [];
  76366. this._tmpPositionVector = BABYLON.Vector3.Zero();
  76367. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  76368. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  76369. this.world.worldscale(1);
  76370. this.world.clear();
  76371. //making sure no stats are calculated
  76372. this.world.isNoStat = true;
  76373. }
  76374. OimoJSPlugin.prototype.setGravity = function (gravity) {
  76375. this.world.gravity.copy(gravity);
  76376. };
  76377. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  76378. this.world.timeStep = timeStep;
  76379. };
  76380. OimoJSPlugin.prototype.getTimeStep = function () {
  76381. return this.world.timeStep;
  76382. };
  76383. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  76384. var _this = this;
  76385. impostors.forEach(function (impostor) {
  76386. impostor.beforeStep();
  76387. });
  76388. this.world.step();
  76389. impostors.forEach(function (impostor) {
  76390. impostor.afterStep();
  76391. //update the ordered impostors array
  76392. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  76393. });
  76394. //check for collisions
  76395. var contact = this.world.contacts;
  76396. while (contact !== null) {
  76397. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  76398. contact = contact.next;
  76399. continue;
  76400. }
  76401. //is this body colliding with any other? get the impostor
  76402. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  76403. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  76404. if (!mainImpostor || !collidingImpostor) {
  76405. contact = contact.next;
  76406. continue;
  76407. }
  76408. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  76409. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  76410. contact = contact.next;
  76411. }
  76412. };
  76413. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76414. var mass = impostor.physicsBody.massInfo.mass;
  76415. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  76416. };
  76417. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76418. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  76419. this.applyImpulse(impostor, force, contactPoint);
  76420. };
  76421. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76422. var _this = this;
  76423. //parent-child relationship. Does this impostor has a parent impostor?
  76424. if (impostor.parent) {
  76425. if (impostor.physicsBody) {
  76426. this.removePhysicsBody(impostor);
  76427. //TODO is that needed?
  76428. impostor.forceUpdate();
  76429. }
  76430. return;
  76431. }
  76432. if (impostor.isBodyInitRequired()) {
  76433. var bodyConfig = {
  76434. name: impostor.uniqueId,
  76435. //Oimo must have mass, also for static objects.
  76436. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  76437. size: [],
  76438. type: [],
  76439. pos: [],
  76440. rot: [],
  76441. move: impostor.getParam("mass") !== 0,
  76442. //Supporting older versions of Oimo
  76443. world: this.world
  76444. };
  76445. var impostors = [impostor];
  76446. var addToArray = function (parent) {
  76447. if (!parent.getChildMeshes)
  76448. return;
  76449. parent.getChildMeshes().forEach(function (m) {
  76450. if (m.physicsImpostor) {
  76451. impostors.push(m.physicsImpostor);
  76452. //m.physicsImpostor._init();
  76453. }
  76454. });
  76455. };
  76456. addToArray(impostor.object);
  76457. var checkWithEpsilon_1 = function (value) {
  76458. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  76459. };
  76460. impostors.forEach(function (i) {
  76461. if (!impostor.object.rotationQuaternion) {
  76462. return;
  76463. }
  76464. //get the correct bounding box
  76465. var oldQuaternion = i.object.rotationQuaternion;
  76466. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  76467. x: impostor.object.rotationQuaternion.x,
  76468. y: impostor.object.rotationQuaternion.y,
  76469. z: impostor.object.rotationQuaternion.z,
  76470. s: impostor.object.rotationQuaternion.w
  76471. });
  76472. var extendSize = i.getObjectExtendSize();
  76473. if (i === impostor) {
  76474. var center = impostor.getObjectCenter();
  76475. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  76476. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  76477. //Can also use Array.prototype.push.apply
  76478. bodyConfig.pos.push(center.x);
  76479. bodyConfig.pos.push(center.y);
  76480. bodyConfig.pos.push(center.z);
  76481. //tmp solution
  76482. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76483. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76484. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76485. }
  76486. else {
  76487. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  76488. bodyConfig.pos.push(localPosition.x);
  76489. bodyConfig.pos.push(localPosition.y);
  76490. bodyConfig.pos.push(localPosition.z);
  76491. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  76492. bodyConfig.rot.push(0);
  76493. bodyConfig.rot.push(0);
  76494. bodyConfig.rot.push(0);
  76495. }
  76496. // register mesh
  76497. switch (i.type) {
  76498. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76499. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  76500. case BABYLON.PhysicsImpostor.SphereImpostor:
  76501. var radiusX = extendSize.x;
  76502. var radiusY = extendSize.y;
  76503. var radiusZ = extendSize.z;
  76504. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  76505. bodyConfig.type.push('sphere');
  76506. //due to the way oimo works with compounds, add 3 times
  76507. bodyConfig.size.push(size);
  76508. bodyConfig.size.push(size);
  76509. bodyConfig.size.push(size);
  76510. break;
  76511. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76512. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  76513. var sizeY = checkWithEpsilon_1(extendSize.y);
  76514. bodyConfig.type.push('cylinder');
  76515. bodyConfig.size.push(sizeX);
  76516. bodyConfig.size.push(sizeY);
  76517. //due to the way oimo works with compounds, add one more value.
  76518. bodyConfig.size.push(sizeY);
  76519. break;
  76520. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76521. case BABYLON.PhysicsImpostor.BoxImpostor:
  76522. default:
  76523. var sizeX = checkWithEpsilon_1(extendSize.x);
  76524. var sizeY = checkWithEpsilon_1(extendSize.y);
  76525. var sizeZ = checkWithEpsilon_1(extendSize.z);
  76526. bodyConfig.type.push('box');
  76527. bodyConfig.size.push(sizeX);
  76528. bodyConfig.size.push(sizeY);
  76529. bodyConfig.size.push(sizeZ);
  76530. break;
  76531. }
  76532. //actually not needed, but hey...
  76533. i.object.rotationQuaternion = oldQuaternion;
  76534. });
  76535. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  76536. }
  76537. else {
  76538. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  76539. }
  76540. impostor.setDeltaPosition(this._tmpPositionVector);
  76541. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  76542. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  76543. };
  76544. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76545. //impostor.physicsBody.dispose();
  76546. //Same as : (older oimo versions)
  76547. this.world.removeRigidBody(impostor.physicsBody);
  76548. };
  76549. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76550. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76551. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76552. if (!mainBody || !connectedBody) {
  76553. return;
  76554. }
  76555. var jointData = impostorJoint.joint.jointData;
  76556. var options = jointData.nativeParams || {};
  76557. var type;
  76558. var nativeJointData = {
  76559. body1: mainBody,
  76560. body2: connectedBody,
  76561. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  76562. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  76563. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  76564. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  76565. min: options.min,
  76566. max: options.max,
  76567. collision: options.collision || jointData.collision,
  76568. spring: options.spring,
  76569. //supporting older version of Oimo
  76570. world: this.world
  76571. };
  76572. switch (impostorJoint.joint.type) {
  76573. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76574. type = "jointBall";
  76575. break;
  76576. case BABYLON.PhysicsJoint.SpringJoint:
  76577. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  76578. var springData = jointData;
  76579. nativeJointData.min = springData.length || nativeJointData.min;
  76580. //Max should also be set, just make sure it is at least min
  76581. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  76582. case BABYLON.PhysicsJoint.DistanceJoint:
  76583. type = "jointDistance";
  76584. nativeJointData.max = jointData.maxDistance;
  76585. break;
  76586. case BABYLON.PhysicsJoint.PrismaticJoint:
  76587. type = "jointPrisme";
  76588. break;
  76589. case BABYLON.PhysicsJoint.SliderJoint:
  76590. type = "jointSlide";
  76591. break;
  76592. case BABYLON.PhysicsJoint.WheelJoint:
  76593. type = "jointWheel";
  76594. break;
  76595. case BABYLON.PhysicsJoint.HingeJoint:
  76596. default:
  76597. type = "jointHinge";
  76598. break;
  76599. }
  76600. nativeJointData.type = type;
  76601. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  76602. };
  76603. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76604. //Bug in Oimo prevents us from disposing a joint in the playground
  76605. //joint.joint.physicsJoint.dispose();
  76606. //So we will bruteforce it!
  76607. try {
  76608. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  76609. }
  76610. catch (e) {
  76611. BABYLON.Tools.Warn(e);
  76612. }
  76613. };
  76614. OimoJSPlugin.prototype.isSupported = function () {
  76615. return this.BJSOIMO !== undefined;
  76616. };
  76617. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76618. if (!impostor.physicsBody.sleeping) {
  76619. //TODO check that
  76620. if (impostor.physicsBody.shapes.next) {
  76621. var parentShape = this._getLastShape(impostor.physicsBody);
  76622. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  76623. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  76624. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  76625. }
  76626. else {
  76627. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  76628. }
  76629. if (impostor.object.rotationQuaternion) {
  76630. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  76631. impostor.object.rotationQuaternion.normalize();
  76632. }
  76633. }
  76634. };
  76635. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76636. var body = impostor.physicsBody;
  76637. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  76638. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  76639. body.syncShapes();
  76640. body.awake();
  76641. };
  76642. OimoJSPlugin.prototype._getLastShape = function (body) {
  76643. var lastShape = body.shapes;
  76644. while (lastShape.next) {
  76645. lastShape = lastShape.next;
  76646. }
  76647. return lastShape;
  76648. };
  76649. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76650. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  76651. };
  76652. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76653. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  76654. };
  76655. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76656. var v = impostor.physicsBody.linearVelocity;
  76657. if (!v) {
  76658. return null;
  76659. }
  76660. return new BABYLON.Vector3(v.x, v.y, v.z);
  76661. };
  76662. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76663. var v = impostor.physicsBody.angularVelocity;
  76664. if (!v) {
  76665. return null;
  76666. }
  76667. return new BABYLON.Vector3(v.x, v.y, v.z);
  76668. };
  76669. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76670. var staticBody = mass === 0;
  76671. //this will actually set the body's density and not its mass.
  76672. //But this is how oimo treats the mass variable.
  76673. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  76674. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  76675. };
  76676. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  76677. return impostor.physicsBody.shapes.density;
  76678. };
  76679. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  76680. return impostor.physicsBody.shapes.friction;
  76681. };
  76682. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76683. impostor.physicsBody.shapes.friction = friction;
  76684. };
  76685. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76686. return impostor.physicsBody.shapes.restitution;
  76687. };
  76688. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76689. impostor.physicsBody.shapes.restitution = restitution;
  76690. };
  76691. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  76692. impostor.physicsBody.sleep();
  76693. };
  76694. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  76695. impostor.physicsBody.awake();
  76696. };
  76697. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76698. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  76699. if (minDistance !== void 0) {
  76700. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  76701. }
  76702. };
  76703. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76704. //TODO separate rotational and transational motors.
  76705. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76706. if (motor) {
  76707. motor.setMotor(speed, maxForce);
  76708. }
  76709. };
  76710. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  76711. //TODO separate rotational and transational motors.
  76712. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76713. if (motor) {
  76714. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  76715. }
  76716. };
  76717. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76718. var body = impostor.physicsBody;
  76719. mesh.position.x = body.position.x;
  76720. mesh.position.y = body.position.y;
  76721. mesh.position.z = body.position.z;
  76722. if (mesh.rotationQuaternion) {
  76723. mesh.rotationQuaternion.x = body.orientation.x;
  76724. mesh.rotationQuaternion.y = body.orientation.y;
  76725. mesh.rotationQuaternion.z = body.orientation.z;
  76726. mesh.rotationQuaternion.w = body.orientation.s;
  76727. }
  76728. };
  76729. OimoJSPlugin.prototype.getRadius = function (impostor) {
  76730. return impostor.physicsBody.shapes.radius;
  76731. };
  76732. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76733. var shape = impostor.physicsBody.shapes;
  76734. result.x = shape.halfWidth * 2;
  76735. result.y = shape.halfHeight * 2;
  76736. result.z = shape.halfDepth * 2;
  76737. };
  76738. OimoJSPlugin.prototype.dispose = function () {
  76739. this.world.clear();
  76740. };
  76741. return OimoJSPlugin;
  76742. }());
  76743. BABYLON.OimoJSPlugin = OimoJSPlugin;
  76744. })(BABYLON || (BABYLON = {}));
  76745. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  76746. var BABYLON;
  76747. (function (BABYLON) {
  76748. /*
  76749. * Based on jsTGALoader - Javascript loader for TGA file
  76750. * By Vincent Thibault
  76751. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  76752. */
  76753. var TGATools = /** @class */ (function () {
  76754. function TGATools() {
  76755. }
  76756. TGATools.GetTGAHeader = function (data) {
  76757. var offset = 0;
  76758. var header = {
  76759. id_length: data[offset++],
  76760. colormap_type: data[offset++],
  76761. image_type: data[offset++],
  76762. colormap_index: data[offset++] | data[offset++] << 8,
  76763. colormap_length: data[offset++] | data[offset++] << 8,
  76764. colormap_size: data[offset++],
  76765. origin: [
  76766. data[offset++] | data[offset++] << 8,
  76767. data[offset++] | data[offset++] << 8
  76768. ],
  76769. width: data[offset++] | data[offset++] << 8,
  76770. height: data[offset++] | data[offset++] << 8,
  76771. pixel_size: data[offset++],
  76772. flags: data[offset++]
  76773. };
  76774. return header;
  76775. };
  76776. TGATools.UploadContent = function (gl, data) {
  76777. // Not enough data to contain header ?
  76778. if (data.length < 19) {
  76779. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  76780. return;
  76781. }
  76782. // Read Header
  76783. var offset = 18;
  76784. var header = TGATools.GetTGAHeader(data);
  76785. // Assume it's a valid Targa file.
  76786. if (header.id_length + offset > data.length) {
  76787. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  76788. return;
  76789. }
  76790. // Skip not needed data
  76791. offset += header.id_length;
  76792. var use_rle = false;
  76793. var use_pal = false;
  76794. var use_grey = false;
  76795. // Get some informations.
  76796. switch (header.image_type) {
  76797. case TGATools._TYPE_RLE_INDEXED:
  76798. use_rle = true;
  76799. case TGATools._TYPE_INDEXED:
  76800. use_pal = true;
  76801. break;
  76802. case TGATools._TYPE_RLE_RGB:
  76803. use_rle = true;
  76804. case TGATools._TYPE_RGB:
  76805. // use_rgb = true;
  76806. break;
  76807. case TGATools._TYPE_RLE_GREY:
  76808. use_rle = true;
  76809. case TGATools._TYPE_GREY:
  76810. use_grey = true;
  76811. break;
  76812. }
  76813. var pixel_data;
  76814. // var numAlphaBits = header.flags & 0xf;
  76815. var pixel_size = header.pixel_size >> 3;
  76816. var pixel_total = header.width * header.height * pixel_size;
  76817. // Read palettes
  76818. var palettes;
  76819. if (use_pal) {
  76820. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  76821. }
  76822. // Read LRE
  76823. if (use_rle) {
  76824. pixel_data = new Uint8Array(pixel_total);
  76825. var c, count, i;
  76826. var localOffset = 0;
  76827. var pixels = new Uint8Array(pixel_size);
  76828. while (offset < pixel_total && localOffset < pixel_total) {
  76829. c = data[offset++];
  76830. count = (c & 0x7f) + 1;
  76831. // RLE pixels
  76832. if (c & 0x80) {
  76833. // Bind pixel tmp array
  76834. for (i = 0; i < pixel_size; ++i) {
  76835. pixels[i] = data[offset++];
  76836. }
  76837. // Copy pixel array
  76838. for (i = 0; i < count; ++i) {
  76839. pixel_data.set(pixels, localOffset + i * pixel_size);
  76840. }
  76841. localOffset += pixel_size * count;
  76842. }
  76843. else {
  76844. count *= pixel_size;
  76845. for (i = 0; i < count; ++i) {
  76846. pixel_data[localOffset + i] = data[offset++];
  76847. }
  76848. localOffset += count;
  76849. }
  76850. }
  76851. }
  76852. else {
  76853. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  76854. }
  76855. // Load to texture
  76856. var x_start, y_start, x_step, y_step, y_end, x_end;
  76857. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  76858. default:
  76859. case TGATools._ORIGIN_UL:
  76860. x_start = 0;
  76861. x_step = 1;
  76862. x_end = header.width;
  76863. y_start = 0;
  76864. y_step = 1;
  76865. y_end = header.height;
  76866. break;
  76867. case TGATools._ORIGIN_BL:
  76868. x_start = 0;
  76869. x_step = 1;
  76870. x_end = header.width;
  76871. y_start = header.height - 1;
  76872. y_step = -1;
  76873. y_end = -1;
  76874. break;
  76875. case TGATools._ORIGIN_UR:
  76876. x_start = header.width - 1;
  76877. x_step = -1;
  76878. x_end = -1;
  76879. y_start = 0;
  76880. y_step = 1;
  76881. y_end = header.height;
  76882. break;
  76883. case TGATools._ORIGIN_BR:
  76884. x_start = header.width - 1;
  76885. x_step = -1;
  76886. x_end = -1;
  76887. y_start = header.height - 1;
  76888. y_step = -1;
  76889. y_end = -1;
  76890. break;
  76891. }
  76892. // Load the specify method
  76893. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  76894. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  76895. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  76896. };
  76897. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76898. var image = pixel_data, colormap = palettes;
  76899. var width = header.width, height = header.height;
  76900. var color, i = 0, x, y;
  76901. var imageData = new Uint8Array(width * height * 4);
  76902. for (y = y_start; y !== y_end; y += y_step) {
  76903. for (x = x_start; x !== x_end; x += x_step, i++) {
  76904. color = image[i];
  76905. imageData[(x + width * y) * 4 + 3] = 255;
  76906. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  76907. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  76908. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  76909. }
  76910. }
  76911. return imageData;
  76912. };
  76913. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76914. var image = pixel_data;
  76915. var width = header.width, height = header.height;
  76916. var color, i = 0, x, y;
  76917. var imageData = new Uint8Array(width * height * 4);
  76918. for (y = y_start; y !== y_end; y += y_step) {
  76919. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  76920. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  76921. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  76922. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  76923. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  76924. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  76925. }
  76926. }
  76927. return imageData;
  76928. };
  76929. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76930. var image = pixel_data;
  76931. var width = header.width, height = header.height;
  76932. var i = 0, x, y;
  76933. var imageData = new Uint8Array(width * height * 4);
  76934. for (y = y_start; y !== y_end; y += y_step) {
  76935. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  76936. imageData[(x + width * y) * 4 + 3] = 255;
  76937. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  76938. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  76939. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  76940. }
  76941. }
  76942. return imageData;
  76943. };
  76944. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76945. var image = pixel_data;
  76946. var width = header.width, height = header.height;
  76947. var i = 0, x, y;
  76948. var imageData = new Uint8Array(width * height * 4);
  76949. for (y = y_start; y !== y_end; y += y_step) {
  76950. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  76951. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  76952. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  76953. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  76954. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  76955. }
  76956. }
  76957. return imageData;
  76958. };
  76959. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76960. var image = pixel_data;
  76961. var width = header.width, height = header.height;
  76962. var color, i = 0, x, y;
  76963. var imageData = new Uint8Array(width * height * 4);
  76964. for (y = y_start; y !== y_end; y += y_step) {
  76965. for (x = x_start; x !== x_end; x += x_step, i++) {
  76966. color = image[i];
  76967. imageData[(x + width * y) * 4 + 0] = color;
  76968. imageData[(x + width * y) * 4 + 1] = color;
  76969. imageData[(x + width * y) * 4 + 2] = color;
  76970. imageData[(x + width * y) * 4 + 3] = 255;
  76971. }
  76972. }
  76973. return imageData;
  76974. };
  76975. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76976. var image = pixel_data;
  76977. var width = header.width, height = header.height;
  76978. var i = 0, x, y;
  76979. var imageData = new Uint8Array(width * height * 4);
  76980. for (y = y_start; y !== y_end; y += y_step) {
  76981. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  76982. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  76983. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  76984. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  76985. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  76986. }
  76987. }
  76988. return imageData;
  76989. };
  76990. //private static _TYPE_NO_DATA = 0;
  76991. TGATools._TYPE_INDEXED = 1;
  76992. TGATools._TYPE_RGB = 2;
  76993. TGATools._TYPE_GREY = 3;
  76994. TGATools._TYPE_RLE_INDEXED = 9;
  76995. TGATools._TYPE_RLE_RGB = 10;
  76996. TGATools._TYPE_RLE_GREY = 11;
  76997. TGATools._ORIGIN_MASK = 0x30;
  76998. TGATools._ORIGIN_SHIFT = 0x04;
  76999. TGATools._ORIGIN_BL = 0x00;
  77000. TGATools._ORIGIN_BR = 0x01;
  77001. TGATools._ORIGIN_UL = 0x02;
  77002. TGATools._ORIGIN_UR = 0x03;
  77003. return TGATools;
  77004. }());
  77005. BABYLON.TGATools = TGATools;
  77006. })(BABYLON || (BABYLON = {}));
  77007. //# sourceMappingURL=babylon.tga.js.map
  77008. var BABYLON;
  77009. (function (BABYLON) {
  77010. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  77011. // All values and structures referenced from:
  77012. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  77013. var DDS_MAGIC = 0x20534444;
  77014. var
  77015. //DDSD_CAPS = 0x1,
  77016. //DDSD_HEIGHT = 0x2,
  77017. //DDSD_WIDTH = 0x4,
  77018. //DDSD_PITCH = 0x8,
  77019. //DDSD_PIXELFORMAT = 0x1000,
  77020. DDSD_MIPMAPCOUNT = 0x20000;
  77021. //DDSD_LINEARSIZE = 0x80000,
  77022. //DDSD_DEPTH = 0x800000;
  77023. // var DDSCAPS_COMPLEX = 0x8,
  77024. // DDSCAPS_MIPMAP = 0x400000,
  77025. // DDSCAPS_TEXTURE = 0x1000;
  77026. var DDSCAPS2_CUBEMAP = 0x200;
  77027. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  77028. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  77029. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  77030. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  77031. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  77032. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  77033. // DDSCAPS2_VOLUME = 0x200000;
  77034. var
  77035. //DDPF_ALPHAPIXELS = 0x1,
  77036. //DDPF_ALPHA = 0x2,
  77037. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  77038. //DDPF_YUV = 0x200,
  77039. DDPF_LUMINANCE = 0x20000;
  77040. function FourCCToInt32(value) {
  77041. return value.charCodeAt(0) +
  77042. (value.charCodeAt(1) << 8) +
  77043. (value.charCodeAt(2) << 16) +
  77044. (value.charCodeAt(3) << 24);
  77045. }
  77046. function Int32ToFourCC(value) {
  77047. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  77048. }
  77049. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  77050. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  77051. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  77052. var FOURCC_DX10 = FourCCToInt32("DX10");
  77053. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  77054. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  77055. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  77056. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  77057. var headerLengthInt = 31; // The header length in 32 bit ints
  77058. // Offsets into the header array
  77059. var off_magic = 0;
  77060. var off_size = 1;
  77061. var off_flags = 2;
  77062. var off_height = 3;
  77063. var off_width = 4;
  77064. var off_mipmapCount = 7;
  77065. var off_pfFlags = 20;
  77066. var off_pfFourCC = 21;
  77067. var off_RGBbpp = 22;
  77068. var off_RMask = 23;
  77069. var off_GMask = 24;
  77070. var off_BMask = 25;
  77071. var off_AMask = 26;
  77072. // var off_caps1 = 27;
  77073. var off_caps2 = 28;
  77074. // var off_caps3 = 29;
  77075. // var off_caps4 = 30;
  77076. var off_dxgiFormat = 32;
  77077. ;
  77078. var DDSTools = /** @class */ (function () {
  77079. function DDSTools() {
  77080. }
  77081. DDSTools.GetDDSInfo = function (arrayBuffer) {
  77082. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77083. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  77084. var mipmapCount = 1;
  77085. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  77086. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77087. }
  77088. var fourCC = header[off_pfFourCC];
  77089. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  77090. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77091. switch (fourCC) {
  77092. case FOURCC_D3DFMT_R16G16B16A16F:
  77093. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77094. break;
  77095. case FOURCC_D3DFMT_R32G32B32A32F:
  77096. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77097. break;
  77098. case FOURCC_DX10:
  77099. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  77100. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77101. break;
  77102. }
  77103. }
  77104. return {
  77105. width: header[off_width],
  77106. height: header[off_height],
  77107. mipmapCount: mipmapCount,
  77108. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  77109. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  77110. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  77111. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  77112. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  77113. dxgiFormat: dxgiFormat,
  77114. textureType: textureType
  77115. };
  77116. };
  77117. DDSTools._ToHalfFloat = function (value) {
  77118. if (!DDSTools._FloatView) {
  77119. DDSTools._FloatView = new Float32Array(1);
  77120. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  77121. }
  77122. DDSTools._FloatView[0] = value;
  77123. var x = DDSTools._Int32View[0];
  77124. var bits = (x >> 16) & 0x8000; /* Get the sign */
  77125. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  77126. var e = (x >> 23) & 0xff; /* Using int is faster here */
  77127. /* If zero, or denormal, or exponent underflows too much for a denormal
  77128. * half, return signed zero. */
  77129. if (e < 103) {
  77130. return bits;
  77131. }
  77132. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  77133. if (e > 142) {
  77134. bits |= 0x7c00;
  77135. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  77136. * not Inf, so make sure we set one mantissa bit too. */
  77137. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  77138. return bits;
  77139. }
  77140. /* If exponent underflows but not too much, return a denormal */
  77141. if (e < 113) {
  77142. m |= 0x0800;
  77143. /* Extra rounding may overflow and set mantissa to 0 and exponent
  77144. * to 1, which is OK. */
  77145. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  77146. return bits;
  77147. }
  77148. bits |= ((e - 112) << 10) | (m >> 1);
  77149. bits += m & 1;
  77150. return bits;
  77151. };
  77152. DDSTools._FromHalfFloat = function (value) {
  77153. var s = (value & 0x8000) >> 15;
  77154. var e = (value & 0x7C00) >> 10;
  77155. var f = value & 0x03FF;
  77156. if (e === 0) {
  77157. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  77158. }
  77159. else if (e == 0x1F) {
  77160. return f ? NaN : ((s ? -1 : 1) * Infinity);
  77161. }
  77162. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  77163. };
  77164. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77165. var destArray = new Float32Array(dataLength);
  77166. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77167. var index = 0;
  77168. for (var y = 0; y < height; y++) {
  77169. for (var x = 0; x < width; x++) {
  77170. var srcPos = (x + y * width) * 4;
  77171. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  77172. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  77173. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  77174. if (DDSTools.StoreLODInAlphaChannel) {
  77175. destArray[index + 3] = lod;
  77176. }
  77177. else {
  77178. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  77179. }
  77180. index += 4;
  77181. }
  77182. }
  77183. return destArray;
  77184. };
  77185. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77186. if (DDSTools.StoreLODInAlphaChannel) {
  77187. var destArray = new Uint16Array(dataLength);
  77188. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77189. var index = 0;
  77190. for (var y = 0; y < height; y++) {
  77191. for (var x = 0; x < width; x++) {
  77192. var srcPos = (x + y * width) * 4;
  77193. destArray[index] = srcData[srcPos];
  77194. destArray[index + 1] = srcData[srcPos + 1];
  77195. destArray[index + 2] = srcData[srcPos + 2];
  77196. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  77197. index += 4;
  77198. }
  77199. }
  77200. return destArray;
  77201. }
  77202. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  77203. };
  77204. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77205. if (DDSTools.StoreLODInAlphaChannel) {
  77206. var destArray = new Float32Array(dataLength);
  77207. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77208. var index = 0;
  77209. for (var y = 0; y < height; y++) {
  77210. for (var x = 0; x < width; x++) {
  77211. var srcPos = (x + y * width) * 4;
  77212. destArray[index] = srcData[srcPos];
  77213. destArray[index + 1] = srcData[srcPos + 1];
  77214. destArray[index + 2] = srcData[srcPos + 2];
  77215. destArray[index + 3] = lod;
  77216. index += 4;
  77217. }
  77218. }
  77219. return destArray;
  77220. }
  77221. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  77222. };
  77223. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77224. var destArray = new Uint8Array(dataLength);
  77225. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77226. var index = 0;
  77227. for (var y = 0; y < height; y++) {
  77228. for (var x = 0; x < width; x++) {
  77229. var srcPos = (x + y * width) * 4;
  77230. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  77231. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  77232. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  77233. if (DDSTools.StoreLODInAlphaChannel) {
  77234. destArray[index + 3] = lod;
  77235. }
  77236. else {
  77237. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  77238. }
  77239. index += 4;
  77240. }
  77241. }
  77242. return destArray;
  77243. };
  77244. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77245. var destArray = new Uint8Array(dataLength);
  77246. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77247. var index = 0;
  77248. for (var y = 0; y < height; y++) {
  77249. for (var x = 0; x < width; x++) {
  77250. var srcPos = (x + y * width) * 4;
  77251. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  77252. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  77253. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  77254. if (DDSTools.StoreLODInAlphaChannel) {
  77255. destArray[index + 3] = lod;
  77256. }
  77257. else {
  77258. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  77259. }
  77260. index += 4;
  77261. }
  77262. }
  77263. return destArray;
  77264. };
  77265. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  77266. var byteArray = new Uint8Array(dataLength);
  77267. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77268. var index = 0;
  77269. for (var y = 0; y < height; y++) {
  77270. for (var x = 0; x < width; x++) {
  77271. var srcPos = (x + y * width) * 4;
  77272. byteArray[index] = srcData[srcPos + rOffset];
  77273. byteArray[index + 1] = srcData[srcPos + gOffset];
  77274. byteArray[index + 2] = srcData[srcPos + bOffset];
  77275. byteArray[index + 3] = srcData[srcPos + aOffset];
  77276. index += 4;
  77277. }
  77278. }
  77279. return byteArray;
  77280. };
  77281. DDSTools._ExtractLongWordOrder = function (value) {
  77282. if (value === 0 || value === 255 || value === -16777216) {
  77283. return 0;
  77284. }
  77285. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  77286. };
  77287. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  77288. var byteArray = new Uint8Array(dataLength);
  77289. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77290. var index = 0;
  77291. for (var y = 0; y < height; y++) {
  77292. for (var x = 0; x < width; x++) {
  77293. var srcPos = (x + y * width) * 3;
  77294. byteArray[index] = srcData[srcPos + rOffset];
  77295. byteArray[index + 1] = srcData[srcPos + gOffset];
  77296. byteArray[index + 2] = srcData[srcPos + bOffset];
  77297. index += 3;
  77298. }
  77299. }
  77300. return byteArray;
  77301. };
  77302. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  77303. var byteArray = new Uint8Array(dataLength);
  77304. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77305. var index = 0;
  77306. for (var y = 0; y < height; y++) {
  77307. for (var x = 0; x < width; x++) {
  77308. var srcPos = (x + y * width);
  77309. byteArray[index] = srcData[srcPos];
  77310. index++;
  77311. }
  77312. }
  77313. return byteArray;
  77314. };
  77315. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  77316. if (lodIndex === void 0) { lodIndex = -1; }
  77317. var ext = engine.getCaps().s3tc;
  77318. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77319. var fourCC, width, height, dataLength = 0, dataOffset;
  77320. var byteArray, mipmapCount, mip;
  77321. var internalFormat = 0;
  77322. var format = 0;
  77323. var blockBytes = 1;
  77324. if (header[off_magic] !== DDS_MAGIC) {
  77325. BABYLON.Tools.Error("Invalid magic number in DDS header");
  77326. return;
  77327. }
  77328. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  77329. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  77330. return;
  77331. }
  77332. if (info.isCompressed && !ext) {
  77333. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  77334. return;
  77335. }
  77336. var bpp = header[off_RGBbpp];
  77337. dataOffset = header[off_size] + 4;
  77338. var computeFormats = false;
  77339. if (info.isFourCC) {
  77340. fourCC = header[off_pfFourCC];
  77341. switch (fourCC) {
  77342. case FOURCC_DXT1:
  77343. blockBytes = 8;
  77344. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  77345. break;
  77346. case FOURCC_DXT3:
  77347. blockBytes = 16;
  77348. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  77349. break;
  77350. case FOURCC_DXT5:
  77351. blockBytes = 16;
  77352. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  77353. break;
  77354. case FOURCC_D3DFMT_R16G16B16A16F:
  77355. computeFormats = true;
  77356. break;
  77357. case FOURCC_D3DFMT_R32G32B32A32F:
  77358. computeFormats = true;
  77359. break;
  77360. case FOURCC_DX10:
  77361. // There is an additionnal header so dataOffset need to be changed
  77362. dataOffset += 5 * 4; // 5 uints
  77363. var supported = false;
  77364. switch (info.dxgiFormat) {
  77365. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  77366. computeFormats = true;
  77367. supported = true;
  77368. break;
  77369. case DXGI_FORMAT_B8G8R8X8_UNORM:
  77370. info.isRGB = true;
  77371. info.isFourCC = false;
  77372. bpp = 32;
  77373. supported = true;
  77374. break;
  77375. }
  77376. if (supported) {
  77377. break;
  77378. }
  77379. default:
  77380. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  77381. return;
  77382. }
  77383. }
  77384. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  77385. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  77386. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  77387. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  77388. if (computeFormats) {
  77389. format = engine._getWebGLTextureType(info.textureType);
  77390. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77391. }
  77392. mipmapCount = 1;
  77393. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  77394. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77395. }
  77396. for (var face = 0; face < faces; face++) {
  77397. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  77398. width = header[off_width];
  77399. height = header[off_height];
  77400. for (mip = 0; mip < mipmapCount; ++mip) {
  77401. if (lodIndex === -1 || lodIndex === mip) {
  77402. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  77403. var i = (lodIndex === -1) ? mip : 0;
  77404. if (!info.isCompressed && info.isFourCC) {
  77405. dataLength = width * height * 4;
  77406. var floatArray = null;
  77407. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  77408. if (bpp === 128) {
  77409. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77410. }
  77411. else if (bpp === 64) {
  77412. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77413. }
  77414. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77415. format = engine._getWebGLTextureType(info.textureType);
  77416. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77417. }
  77418. else {
  77419. if (bpp === 128) {
  77420. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77421. }
  77422. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  77423. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77424. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77425. format = engine._getWebGLTextureType(info.textureType);
  77426. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77427. }
  77428. else {
  77429. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77430. }
  77431. }
  77432. if (floatArray) {
  77433. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  77434. }
  77435. }
  77436. else if (info.isRGB) {
  77437. if (bpp === 24) {
  77438. dataLength = width * height * 3;
  77439. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  77440. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  77441. }
  77442. else {
  77443. dataLength = width * height * 4;
  77444. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  77445. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  77446. }
  77447. }
  77448. else if (info.isLuminance) {
  77449. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  77450. var unpaddedRowSize = width;
  77451. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  77452. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  77453. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  77454. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  77455. }
  77456. else {
  77457. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  77458. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  77459. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  77460. }
  77461. }
  77462. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  77463. width *= 0.5;
  77464. height *= 0.5;
  77465. width = Math.max(1.0, width);
  77466. height = Math.max(1.0, height);
  77467. }
  77468. if (currentFace !== undefined) {
  77469. // Loading a single face
  77470. break;
  77471. }
  77472. }
  77473. };
  77474. DDSTools.StoreLODInAlphaChannel = false;
  77475. return DDSTools;
  77476. }());
  77477. BABYLON.DDSTools = DDSTools;
  77478. })(BABYLON || (BABYLON = {}));
  77479. //# sourceMappingURL=babylon.dds.js.map
  77480. var BABYLON;
  77481. (function (BABYLON) {
  77482. /**
  77483. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  77484. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  77485. */
  77486. var KhronosTextureContainer = /** @class */ (function () {
  77487. /**
  77488. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  77489. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  77490. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  77491. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  77492. */
  77493. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  77494. this.arrayBuffer = arrayBuffer;
  77495. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  77496. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  77497. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  77498. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  77499. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  77500. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  77501. BABYLON.Tools.Error("texture missing KTX identifier");
  77502. return;
  77503. }
  77504. // load the reset of the header in native 32 bit int
  77505. var header = new Int32Array(this.arrayBuffer, 12, 13);
  77506. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  77507. var oppositeEndianess = header[0] === 0x01020304;
  77508. // read all the header elements in order they exist in the file, without modification (sans endainness)
  77509. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  77510. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  77511. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  77512. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  77513. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  77514. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  77515. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  77516. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  77517. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  77518. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  77519. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  77520. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  77521. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  77522. if (this.glType !== 0) {
  77523. BABYLON.Tools.Error("only compressed formats currently supported");
  77524. return;
  77525. }
  77526. else {
  77527. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  77528. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  77529. }
  77530. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  77531. BABYLON.Tools.Error("only 2D textures currently supported");
  77532. return;
  77533. }
  77534. if (this.numberOfArrayElements !== 0) {
  77535. BABYLON.Tools.Error("texture arrays not currently supported");
  77536. return;
  77537. }
  77538. if (this.numberOfFaces !== facesExpected) {
  77539. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  77540. return;
  77541. }
  77542. // we now have a completely validated file, so could use existence of loadType as success
  77543. // would need to make this more elaborate & adjust checks above to support more than one load type
  77544. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  77545. }
  77546. // not as fast hardware based, but will probably never need to use
  77547. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  77548. return ((val & 0xFF) << 24)
  77549. | ((val & 0xFF00) << 8)
  77550. | ((val >> 8) & 0xFF00)
  77551. | ((val >> 24) & 0xFF);
  77552. };
  77553. /**
  77554. * It is assumed that the texture has already been created & is currently bound
  77555. */
  77556. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  77557. switch (this.loadType) {
  77558. case KhronosTextureContainer.COMPRESSED_2D:
  77559. this._upload2DCompressedLevels(gl, loadMipmaps);
  77560. break;
  77561. case KhronosTextureContainer.TEX_2D:
  77562. case KhronosTextureContainer.COMPRESSED_3D:
  77563. case KhronosTextureContainer.TEX_3D:
  77564. }
  77565. };
  77566. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  77567. // initialize width & height for level 1
  77568. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  77569. var width = this.pixelWidth;
  77570. var height = this.pixelHeight;
  77571. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  77572. for (var level = 0; level < mipmapCount; level++) {
  77573. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  77574. for (var face = 0; face < this.numberOfFaces; face++) {
  77575. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  77576. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  77577. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  77578. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  77579. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  77580. }
  77581. width = Math.max(1.0, width * 0.5);
  77582. height = Math.max(1.0, height * 0.5);
  77583. }
  77584. };
  77585. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  77586. // load types
  77587. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  77588. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  77589. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  77590. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  77591. return KhronosTextureContainer;
  77592. }());
  77593. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  77594. })(BABYLON || (BABYLON = {}));
  77595. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  77596. var BABYLON;
  77597. (function (BABYLON) {
  77598. var Debug = /** @class */ (function () {
  77599. function Debug() {
  77600. }
  77601. Debug.AxesViewer = /** @class */ (function () {
  77602. function AxesViewer(scene, scaleLines) {
  77603. if (scaleLines === void 0) { scaleLines = 1; }
  77604. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77605. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77606. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77607. this.scaleLines = 1;
  77608. this.scaleLines = scaleLines;
  77609. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  77610. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  77611. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  77612. this._xmesh.renderingGroupId = 2;
  77613. this._ymesh.renderingGroupId = 2;
  77614. this._zmesh.renderingGroupId = 2;
  77615. this._xmesh.material.checkReadyOnlyOnce = true;
  77616. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  77617. this._ymesh.material.checkReadyOnlyOnce = true;
  77618. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  77619. this._zmesh.material.checkReadyOnlyOnce = true;
  77620. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  77621. this.scene = scene;
  77622. }
  77623. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  77624. var scaleLines = this.scaleLines;
  77625. if (this._xmesh) {
  77626. this._xmesh.position.copyFrom(position);
  77627. }
  77628. if (this._ymesh) {
  77629. this._ymesh.position.copyFrom(position);
  77630. }
  77631. if (this._zmesh) {
  77632. this._zmesh.position.copyFrom(position);
  77633. }
  77634. var point2 = this._xline[1];
  77635. point2.x = xaxis.x * scaleLines;
  77636. point2.y = xaxis.y * scaleLines;
  77637. point2.z = xaxis.z * scaleLines;
  77638. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  77639. point2 = this._yline[1];
  77640. point2.x = yaxis.x * scaleLines;
  77641. point2.y = yaxis.y * scaleLines;
  77642. point2.z = yaxis.z * scaleLines;
  77643. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  77644. point2 = this._zline[1];
  77645. point2.x = zaxis.x * scaleLines;
  77646. point2.y = zaxis.y * scaleLines;
  77647. point2.z = zaxis.z * scaleLines;
  77648. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  77649. };
  77650. AxesViewer.prototype.dispose = function () {
  77651. if (this._xmesh) {
  77652. this._xmesh.dispose();
  77653. }
  77654. if (this._ymesh) {
  77655. this._ymesh.dispose();
  77656. }
  77657. if (this._zmesh) {
  77658. this._zmesh.dispose();
  77659. }
  77660. this._xmesh = null;
  77661. this._ymesh = null;
  77662. this._zmesh = null;
  77663. this.scene = null;
  77664. };
  77665. return AxesViewer;
  77666. }());
  77667. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  77668. __extends(BoneAxesViewer, _super);
  77669. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  77670. if (scaleLines === void 0) { scaleLines = 1; }
  77671. var _this = _super.call(this, scene, scaleLines) || this;
  77672. _this.pos = BABYLON.Vector3.Zero();
  77673. _this.xaxis = BABYLON.Vector3.Zero();
  77674. _this.yaxis = BABYLON.Vector3.Zero();
  77675. _this.zaxis = BABYLON.Vector3.Zero();
  77676. _this.mesh = mesh;
  77677. _this.bone = bone;
  77678. return _this;
  77679. }
  77680. BoneAxesViewer.prototype.update = function () {
  77681. if (!this.mesh || !this.bone) {
  77682. return;
  77683. }
  77684. var bone = this.bone;
  77685. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  77686. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  77687. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  77688. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  77689. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  77690. };
  77691. BoneAxesViewer.prototype.dispose = function () {
  77692. if (this.mesh) {
  77693. this.mesh = null;
  77694. this.bone = null;
  77695. _super.prototype.dispose.call(this);
  77696. }
  77697. };
  77698. return BoneAxesViewer;
  77699. }(Debug.AxesViewer));
  77700. Debug.PhysicsViewer = /** @class */ (function () {
  77701. function PhysicsViewer(scene) {
  77702. this._impostors = [];
  77703. this._meshes = [];
  77704. this._numMeshes = 0;
  77705. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77706. var physicEngine = this._scene.getPhysicsEngine();
  77707. if (physicEngine) {
  77708. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  77709. }
  77710. }
  77711. PhysicsViewer.prototype._updateDebugMeshes = function () {
  77712. var plugin = this._physicsEnginePlugin;
  77713. for (var i = 0; i < this._numMeshes; i++) {
  77714. var impostor = this._impostors[i];
  77715. if (!impostor) {
  77716. continue;
  77717. }
  77718. if (impostor.isDisposed) {
  77719. this.hideImpostor(this._impostors[i--]);
  77720. }
  77721. else {
  77722. var mesh = this._meshes[i];
  77723. if (mesh && plugin) {
  77724. plugin.syncMeshWithImpostor(mesh, impostor);
  77725. }
  77726. }
  77727. }
  77728. };
  77729. PhysicsViewer.prototype.showImpostor = function (impostor) {
  77730. if (!this._scene) {
  77731. return;
  77732. }
  77733. for (var i = 0; i < this._numMeshes; i++) {
  77734. if (this._impostors[i] == impostor) {
  77735. return;
  77736. }
  77737. }
  77738. var debugMesh = this._getDebugMesh(impostor, this._scene);
  77739. if (debugMesh) {
  77740. this._impostors[this._numMeshes] = impostor;
  77741. this._meshes[this._numMeshes] = debugMesh;
  77742. if (this._numMeshes === 0) {
  77743. this._renderFunction = this._updateDebugMeshes.bind(this);
  77744. this._scene.registerBeforeRender(this._renderFunction);
  77745. }
  77746. this._numMeshes++;
  77747. }
  77748. };
  77749. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  77750. if (!impostor || !this._scene) {
  77751. return;
  77752. }
  77753. var removed = false;
  77754. for (var i = 0; i < this._numMeshes; i++) {
  77755. if (this._impostors[i] == impostor) {
  77756. var mesh = this._meshes[i];
  77757. if (!mesh) {
  77758. continue;
  77759. }
  77760. this._scene.removeMesh(mesh);
  77761. mesh.dispose();
  77762. this._numMeshes--;
  77763. if (this._numMeshes > 0) {
  77764. this._meshes[i] = this._meshes[this._numMeshes];
  77765. this._impostors[i] = this._impostors[this._numMeshes];
  77766. this._meshes[this._numMeshes] = null;
  77767. this._impostors[this._numMeshes] = null;
  77768. }
  77769. else {
  77770. this._meshes[0] = null;
  77771. this._impostors[0] = null;
  77772. }
  77773. removed = true;
  77774. break;
  77775. }
  77776. }
  77777. if (removed && this._numMeshes === 0) {
  77778. this._scene.unregisterBeforeRender(this._renderFunction);
  77779. }
  77780. };
  77781. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  77782. if (!this._debugMaterial) {
  77783. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  77784. this._debugMaterial.wireframe = true;
  77785. }
  77786. return this._debugMaterial;
  77787. };
  77788. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  77789. if (!this._debugBoxMesh) {
  77790. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  77791. this._debugBoxMesh.renderingGroupId = 1;
  77792. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  77793. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  77794. scene.removeMesh(this._debugBoxMesh);
  77795. }
  77796. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  77797. };
  77798. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  77799. if (!this._debugSphereMesh) {
  77800. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  77801. this._debugSphereMesh.renderingGroupId = 1;
  77802. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  77803. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  77804. scene.removeMesh(this._debugSphereMesh);
  77805. }
  77806. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  77807. };
  77808. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  77809. var mesh = null;
  77810. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  77811. mesh = this._getDebugBoxMesh(scene);
  77812. impostor.getBoxSizeToRef(mesh.scaling);
  77813. }
  77814. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  77815. mesh = this._getDebugSphereMesh(scene);
  77816. var radius = impostor.getRadius();
  77817. mesh.scaling.x = radius * 2;
  77818. mesh.scaling.y = radius * 2;
  77819. mesh.scaling.z = radius * 2;
  77820. }
  77821. return mesh;
  77822. };
  77823. PhysicsViewer.prototype.dispose = function () {
  77824. for (var i = 0; i < this._numMeshes; i++) {
  77825. this.hideImpostor(this._impostors[i]);
  77826. }
  77827. if (this._debugBoxMesh) {
  77828. this._debugBoxMesh.dispose();
  77829. }
  77830. if (this._debugSphereMesh) {
  77831. this._debugSphereMesh.dispose();
  77832. }
  77833. if (this._debugMaterial) {
  77834. this._debugMaterial.dispose();
  77835. }
  77836. this._impostors.length = 0;
  77837. this._scene = null;
  77838. this._physicsEnginePlugin = null;
  77839. };
  77840. return PhysicsViewer;
  77841. }());
  77842. Debug.SkeletonViewer = /** @class */ (function () {
  77843. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  77844. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  77845. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  77846. this.skeleton = skeleton;
  77847. this.mesh = mesh;
  77848. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  77849. this.renderingGroupId = renderingGroupId;
  77850. this.color = BABYLON.Color3.White();
  77851. this._debugLines = new Array();
  77852. this._isEnabled = false;
  77853. this._scene = scene;
  77854. this.update();
  77855. this._renderFunction = this.update.bind(this);
  77856. }
  77857. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  77858. get: function () {
  77859. return this._isEnabled;
  77860. },
  77861. set: function (value) {
  77862. if (this._isEnabled === value) {
  77863. return;
  77864. }
  77865. this._isEnabled = value;
  77866. if (value) {
  77867. this._scene.registerBeforeRender(this._renderFunction);
  77868. }
  77869. else {
  77870. this._scene.unregisterBeforeRender(this._renderFunction);
  77871. }
  77872. },
  77873. enumerable: true,
  77874. configurable: true
  77875. });
  77876. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  77877. if (x === void 0) { x = 0; }
  77878. if (y === void 0) { y = 0; }
  77879. if (z === void 0) { z = 0; }
  77880. var tmat = BABYLON.Tmp.Matrix[0];
  77881. var parentBone = bone.getParent();
  77882. tmat.copyFrom(bone.getLocalMatrix());
  77883. if (x !== 0 || y !== 0 || z !== 0) {
  77884. var tmat2 = BABYLON.Tmp.Matrix[1];
  77885. BABYLON.Matrix.IdentityToRef(tmat2);
  77886. tmat2.m[12] = x;
  77887. tmat2.m[13] = y;
  77888. tmat2.m[14] = z;
  77889. tmat2.multiplyToRef(tmat, tmat);
  77890. }
  77891. if (parentBone) {
  77892. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  77893. }
  77894. tmat.multiplyToRef(meshMat, tmat);
  77895. position.x = tmat.m[12];
  77896. position.y = tmat.m[13];
  77897. position.z = tmat.m[14];
  77898. };
  77899. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  77900. var len = bones.length;
  77901. var meshPos = this.mesh.position;
  77902. for (var i = 0; i < len; i++) {
  77903. var bone = bones[i];
  77904. var points = this._debugLines[i];
  77905. if (!points) {
  77906. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77907. this._debugLines[i] = points;
  77908. }
  77909. this._getBonePosition(points[0], bone, meshMat);
  77910. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  77911. points[0].subtractInPlace(meshPos);
  77912. points[1].subtractInPlace(meshPos);
  77913. }
  77914. };
  77915. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  77916. var len = bones.length;
  77917. var boneNum = 0;
  77918. var meshPos = this.mesh.position;
  77919. for (var i = len - 1; i >= 0; i--) {
  77920. var childBone = bones[i];
  77921. var parentBone = childBone.getParent();
  77922. if (!parentBone) {
  77923. continue;
  77924. }
  77925. var points = this._debugLines[boneNum];
  77926. if (!points) {
  77927. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77928. this._debugLines[boneNum] = points;
  77929. }
  77930. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  77931. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  77932. points[0].subtractInPlace(meshPos);
  77933. points[1].subtractInPlace(meshPos);
  77934. boneNum++;
  77935. }
  77936. };
  77937. SkeletonViewer.prototype.update = function () {
  77938. if (this.autoUpdateBonesMatrices) {
  77939. this.skeleton.computeAbsoluteTransforms();
  77940. }
  77941. if (this.skeleton.bones[0].length === undefined) {
  77942. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  77943. }
  77944. else {
  77945. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  77946. }
  77947. if (!this._debugMesh) {
  77948. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  77949. this._debugMesh.renderingGroupId = this.renderingGroupId;
  77950. }
  77951. else {
  77952. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  77953. }
  77954. this._debugMesh.position.copyFrom(this.mesh.position);
  77955. this._debugMesh.color = this.color;
  77956. };
  77957. SkeletonViewer.prototype.dispose = function () {
  77958. if (this._debugMesh) {
  77959. this.isEnabled = false;
  77960. this._debugMesh.dispose();
  77961. this._debugMesh = null;
  77962. }
  77963. };
  77964. return SkeletonViewer;
  77965. }());
  77966. return Debug;
  77967. }());
  77968. BABYLON.Debug = Debug;
  77969. })(BABYLON || (BABYLON = {}));
  77970. //# sourceMappingURL=babylon.debugModules.js.map
  77971. var BABYLON;
  77972. (function (BABYLON) {
  77973. var RayHelper = /** @class */ (function () {
  77974. function RayHelper(ray) {
  77975. this.ray = ray;
  77976. }
  77977. RayHelper.CreateAndShow = function (ray, scene, color) {
  77978. var helper = new RayHelper(ray);
  77979. helper.show(scene, color);
  77980. return helper;
  77981. };
  77982. RayHelper.prototype.show = function (scene, color) {
  77983. if (!this._renderFunction && this.ray) {
  77984. var ray = this.ray;
  77985. this._renderFunction = this._render.bind(this);
  77986. this._scene = scene;
  77987. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  77988. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  77989. if (this._renderFunction) {
  77990. this._scene.registerBeforeRender(this._renderFunction);
  77991. }
  77992. }
  77993. if (color && this._renderLine) {
  77994. this._renderLine.color.copyFrom(color);
  77995. }
  77996. };
  77997. RayHelper.prototype.hide = function () {
  77998. if (this._renderFunction && this._scene) {
  77999. this._scene.unregisterBeforeRender(this._renderFunction);
  78000. this._scene = null;
  78001. this._renderFunction = null;
  78002. if (this._renderLine) {
  78003. this._renderLine.dispose();
  78004. this._renderLine = null;
  78005. }
  78006. this._renderPoints = [];
  78007. }
  78008. };
  78009. RayHelper.prototype._render = function () {
  78010. var ray = this.ray;
  78011. if (!ray) {
  78012. return;
  78013. }
  78014. var point = this._renderPoints[1];
  78015. var len = Math.min(ray.length, 1000000);
  78016. point.copyFrom(ray.direction);
  78017. point.scaleInPlace(len);
  78018. point.addInPlace(ray.origin);
  78019. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  78020. };
  78021. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  78022. this._attachedToMesh = mesh;
  78023. var ray = this.ray;
  78024. if (!ray) {
  78025. return;
  78026. }
  78027. if (!ray.direction) {
  78028. ray.direction = BABYLON.Vector3.Zero();
  78029. }
  78030. if (!ray.origin) {
  78031. ray.origin = BABYLON.Vector3.Zero();
  78032. }
  78033. if (length) {
  78034. ray.length = length;
  78035. }
  78036. if (!meshSpaceOrigin) {
  78037. meshSpaceOrigin = BABYLON.Vector3.Zero();
  78038. }
  78039. if (!meshSpaceDirection) {
  78040. // -1 so that this will work with Mesh.lookAt
  78041. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  78042. }
  78043. if (!this._meshSpaceDirection) {
  78044. this._meshSpaceDirection = meshSpaceDirection.clone();
  78045. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  78046. }
  78047. else {
  78048. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  78049. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  78050. }
  78051. if (!this._updateToMeshFunction) {
  78052. this._updateToMeshFunction = this._updateToMesh.bind(this);
  78053. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  78054. }
  78055. this._updateToMesh();
  78056. };
  78057. RayHelper.prototype.detachFromMesh = function () {
  78058. if (this._attachedToMesh) {
  78059. if (this._updateToMeshFunction) {
  78060. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  78061. }
  78062. this._attachedToMesh = null;
  78063. this._updateToMeshFunction = null;
  78064. }
  78065. };
  78066. RayHelper.prototype._updateToMesh = function () {
  78067. var ray = this.ray;
  78068. if (!this._attachedToMesh || !ray) {
  78069. return;
  78070. }
  78071. if (this._attachedToMesh._isDisposed) {
  78072. this.detachFromMesh();
  78073. return;
  78074. }
  78075. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  78076. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  78077. };
  78078. RayHelper.prototype.dispose = function () {
  78079. this.hide();
  78080. this.detachFromMesh();
  78081. this.ray = null;
  78082. };
  78083. return RayHelper;
  78084. }());
  78085. BABYLON.RayHelper = RayHelper;
  78086. })(BABYLON || (BABYLON = {}));
  78087. //# sourceMappingURL=babylon.rayHelper.js.map
  78088. var BABYLON;
  78089. (function (BABYLON) {
  78090. // load the inspector using require, if not present in the global namespace.
  78091. var DebugLayer = /** @class */ (function () {
  78092. function DebugLayer(scene) {
  78093. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78094. this._scene = scene;
  78095. // load inspector using require, if it doesn't exist on the global namespace.
  78096. }
  78097. /** Creates the inspector window. */
  78098. DebugLayer.prototype._createInspector = function (config) {
  78099. if (config === void 0) { config = {}; }
  78100. var popup = config.popup || false;
  78101. var initialTab = config.initialTab || 0;
  78102. var parentElement = config.parentElement || null;
  78103. if (!this._inspector) {
  78104. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78105. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  78106. } // else nothing to do,; instance is already existing
  78107. };
  78108. DebugLayer.prototype.isVisible = function () {
  78109. if (!this._inspector) {
  78110. return false;
  78111. }
  78112. return true;
  78113. };
  78114. DebugLayer.prototype.hide = function () {
  78115. if (this._inspector) {
  78116. try {
  78117. this._inspector.dispose();
  78118. }
  78119. catch (e) {
  78120. // If the inspector has been removed directly from the inspector tool
  78121. }
  78122. this._inspector = null;
  78123. }
  78124. };
  78125. DebugLayer.prototype.show = function (config) {
  78126. if (config === void 0) { config = {}; }
  78127. if (typeof this.BJSINSPECTOR == 'undefined') {
  78128. // Load inspector and add it to the DOM
  78129. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  78130. }
  78131. else {
  78132. // Otherwise creates the inspector
  78133. this._createInspector(config);
  78134. }
  78135. };
  78136. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  78137. return DebugLayer;
  78138. }());
  78139. BABYLON.DebugLayer = DebugLayer;
  78140. })(BABYLON || (BABYLON = {}));
  78141. //# sourceMappingURL=babylon.debugLayer.js.map
  78142. var BABYLON;
  78143. (function (BABYLON) {
  78144. var BoundingBoxRenderer = /** @class */ (function () {
  78145. function BoundingBoxRenderer(scene) {
  78146. this.frontColor = new BABYLON.Color3(1, 1, 1);
  78147. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  78148. this.showBackLines = true;
  78149. this.renderList = new BABYLON.SmartArray(32);
  78150. this._vertexBuffers = {};
  78151. this._scene = scene;
  78152. }
  78153. BoundingBoxRenderer.prototype._prepareRessources = function () {
  78154. if (this._colorShader) {
  78155. return;
  78156. }
  78157. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  78158. attributes: [BABYLON.VertexBuffer.PositionKind],
  78159. uniforms: ["world", "viewProjection", "color"]
  78160. });
  78161. var engine = this._scene.getEngine();
  78162. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  78163. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  78164. this._createIndexBuffer();
  78165. };
  78166. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  78167. var engine = this._scene.getEngine();
  78168. 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]);
  78169. };
  78170. BoundingBoxRenderer.prototype._rebuild = function () {
  78171. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78172. if (vb) {
  78173. vb._rebuild();
  78174. }
  78175. this._createIndexBuffer();
  78176. };
  78177. BoundingBoxRenderer.prototype.reset = function () {
  78178. this.renderList.reset();
  78179. };
  78180. BoundingBoxRenderer.prototype.render = function () {
  78181. if (this.renderList.length === 0) {
  78182. return;
  78183. }
  78184. this._prepareRessources();
  78185. if (!this._colorShader.isReady()) {
  78186. return;
  78187. }
  78188. var engine = this._scene.getEngine();
  78189. engine.setDepthWrite(false);
  78190. this._colorShader._preBind();
  78191. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  78192. var boundingBox = this.renderList.data[boundingBoxIndex];
  78193. var min = boundingBox.minimum;
  78194. var max = boundingBox.maximum;
  78195. var diff = max.subtract(min);
  78196. var median = min.add(diff.scale(0.5));
  78197. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78198. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78199. .multiply(boundingBox.getWorldMatrix());
  78200. // VBOs
  78201. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78202. if (this.showBackLines) {
  78203. // Back
  78204. engine.setDepthFunctionToGreaterOrEqual();
  78205. this._scene.resetCachedMaterial();
  78206. this._colorShader.setColor4("color", this.backColor.toColor4());
  78207. this._colorShader.bind(worldMatrix);
  78208. // Draw order
  78209. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78210. }
  78211. // Front
  78212. engine.setDepthFunctionToLess();
  78213. this._scene.resetCachedMaterial();
  78214. this._colorShader.setColor4("color", this.frontColor.toColor4());
  78215. this._colorShader.bind(worldMatrix);
  78216. // Draw order
  78217. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78218. }
  78219. this._colorShader.unbind();
  78220. engine.setDepthFunctionToLessOrEqual();
  78221. engine.setDepthWrite(true);
  78222. };
  78223. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  78224. this._prepareRessources();
  78225. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  78226. return;
  78227. }
  78228. var engine = this._scene.getEngine();
  78229. engine.setDepthWrite(false);
  78230. engine.setColorWrite(false);
  78231. this._colorShader._preBind();
  78232. var boundingBox = mesh._boundingInfo.boundingBox;
  78233. var min = boundingBox.minimum;
  78234. var max = boundingBox.maximum;
  78235. var diff = max.subtract(min);
  78236. var median = min.add(diff.scale(0.5));
  78237. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78238. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78239. .multiply(boundingBox.getWorldMatrix());
  78240. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78241. engine.setDepthFunctionToLess();
  78242. this._scene.resetCachedMaterial();
  78243. this._colorShader.bind(worldMatrix);
  78244. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78245. this._colorShader.unbind();
  78246. engine.setDepthFunctionToLessOrEqual();
  78247. engine.setDepthWrite(true);
  78248. engine.setColorWrite(true);
  78249. };
  78250. BoundingBoxRenderer.prototype.dispose = function () {
  78251. if (!this._colorShader) {
  78252. return;
  78253. }
  78254. this.renderList.dispose();
  78255. this._colorShader.dispose();
  78256. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78257. if (buffer) {
  78258. buffer.dispose();
  78259. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78260. }
  78261. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78262. };
  78263. return BoundingBoxRenderer;
  78264. }());
  78265. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  78266. })(BABYLON || (BABYLON = {}));
  78267. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  78268. var BABYLON;
  78269. (function (BABYLON) {
  78270. var MorphTarget = /** @class */ (function () {
  78271. function MorphTarget(name, influence) {
  78272. if (influence === void 0) { influence = 0; }
  78273. this.name = name;
  78274. this.animations = new Array();
  78275. this._positions = null;
  78276. this._normals = null;
  78277. this._tangents = null;
  78278. this.onInfluenceChanged = new BABYLON.Observable();
  78279. this.influence = influence;
  78280. }
  78281. Object.defineProperty(MorphTarget.prototype, "influence", {
  78282. get: function () {
  78283. return this._influence;
  78284. },
  78285. set: function (influence) {
  78286. if (this._influence === influence) {
  78287. return;
  78288. }
  78289. var previous = this._influence;
  78290. this._influence = influence;
  78291. if (this.onInfluenceChanged.hasObservers) {
  78292. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  78293. }
  78294. },
  78295. enumerable: true,
  78296. configurable: true
  78297. });
  78298. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  78299. get: function () {
  78300. return !!this._positions;
  78301. },
  78302. enumerable: true,
  78303. configurable: true
  78304. });
  78305. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  78306. get: function () {
  78307. return !!this._normals;
  78308. },
  78309. enumerable: true,
  78310. configurable: true
  78311. });
  78312. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  78313. get: function () {
  78314. return !!this._tangents;
  78315. },
  78316. enumerable: true,
  78317. configurable: true
  78318. });
  78319. MorphTarget.prototype.setPositions = function (data) {
  78320. this._positions = data;
  78321. };
  78322. MorphTarget.prototype.getPositions = function () {
  78323. return this._positions;
  78324. };
  78325. MorphTarget.prototype.setNormals = function (data) {
  78326. this._normals = data;
  78327. };
  78328. MorphTarget.prototype.getNormals = function () {
  78329. return this._normals;
  78330. };
  78331. MorphTarget.prototype.setTangents = function (data) {
  78332. this._tangents = data;
  78333. };
  78334. MorphTarget.prototype.getTangents = function () {
  78335. return this._tangents;
  78336. };
  78337. /**
  78338. * Serializes the current target into a Serialization object.
  78339. * Returns the serialized object.
  78340. */
  78341. MorphTarget.prototype.serialize = function () {
  78342. var serializationObject = {};
  78343. serializationObject.name = this.name;
  78344. serializationObject.influence = this.influence;
  78345. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  78346. if (this.hasNormals) {
  78347. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  78348. }
  78349. if (this.hasTangents) {
  78350. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  78351. }
  78352. // Animations
  78353. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  78354. return serializationObject;
  78355. };
  78356. // Statics
  78357. MorphTarget.Parse = function (serializationObject) {
  78358. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  78359. result.setPositions(serializationObject.positions);
  78360. if (serializationObject.normals) {
  78361. result.setNormals(serializationObject.normals);
  78362. }
  78363. if (serializationObject.tangents) {
  78364. result.setTangents(serializationObject.tangents);
  78365. }
  78366. // Animations
  78367. if (serializationObject.animations) {
  78368. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  78369. var parsedAnimation = serializationObject.animations[animationIndex];
  78370. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  78371. }
  78372. }
  78373. return result;
  78374. };
  78375. MorphTarget.FromMesh = function (mesh, name, influence) {
  78376. if (!name) {
  78377. name = mesh.name;
  78378. }
  78379. var result = new MorphTarget(name, influence);
  78380. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78381. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  78382. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  78383. }
  78384. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  78385. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  78386. }
  78387. return result;
  78388. };
  78389. return MorphTarget;
  78390. }());
  78391. BABYLON.MorphTarget = MorphTarget;
  78392. })(BABYLON || (BABYLON = {}));
  78393. //# sourceMappingURL=babylon.morphTarget.js.map
  78394. var BABYLON;
  78395. (function (BABYLON) {
  78396. var MorphTargetManager = /** @class */ (function () {
  78397. function MorphTargetManager(scene) {
  78398. if (scene === void 0) { scene = null; }
  78399. this._targets = new Array();
  78400. this._targetObservable = new Array();
  78401. this._activeTargets = new BABYLON.SmartArray(16);
  78402. this._supportsNormals = false;
  78403. this._supportsTangents = false;
  78404. this._vertexCount = 0;
  78405. this._uniqueId = 0;
  78406. this._tempInfluences = new Array();
  78407. if (!scene) {
  78408. scene = BABYLON.Engine.LastCreatedScene;
  78409. }
  78410. this._scene = scene;
  78411. if (this._scene) {
  78412. this._scene.morphTargetManagers.push(this);
  78413. this._uniqueId = this._scene.getUniqueId();
  78414. }
  78415. }
  78416. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  78417. get: function () {
  78418. return this._uniqueId;
  78419. },
  78420. enumerable: true,
  78421. configurable: true
  78422. });
  78423. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  78424. get: function () {
  78425. return this._vertexCount;
  78426. },
  78427. enumerable: true,
  78428. configurable: true
  78429. });
  78430. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  78431. get: function () {
  78432. return this._supportsNormals;
  78433. },
  78434. enumerable: true,
  78435. configurable: true
  78436. });
  78437. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  78438. get: function () {
  78439. return this._supportsTangents;
  78440. },
  78441. enumerable: true,
  78442. configurable: true
  78443. });
  78444. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  78445. get: function () {
  78446. return this._targets.length;
  78447. },
  78448. enumerable: true,
  78449. configurable: true
  78450. });
  78451. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  78452. get: function () {
  78453. return this._activeTargets.length;
  78454. },
  78455. enumerable: true,
  78456. configurable: true
  78457. });
  78458. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  78459. get: function () {
  78460. return this._influences;
  78461. },
  78462. enumerable: true,
  78463. configurable: true
  78464. });
  78465. MorphTargetManager.prototype.getActiveTarget = function (index) {
  78466. return this._activeTargets.data[index];
  78467. };
  78468. MorphTargetManager.prototype.getTarget = function (index) {
  78469. return this._targets[index];
  78470. };
  78471. MorphTargetManager.prototype.addTarget = function (target) {
  78472. var _this = this;
  78473. this._targets.push(target);
  78474. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  78475. _this._syncActiveTargets(needUpdate);
  78476. }));
  78477. this._syncActiveTargets(true);
  78478. };
  78479. MorphTargetManager.prototype.removeTarget = function (target) {
  78480. var index = this._targets.indexOf(target);
  78481. if (index >= 0) {
  78482. this._targets.splice(index, 1);
  78483. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  78484. this._syncActiveTargets(true);
  78485. }
  78486. };
  78487. /**
  78488. * Serializes the current manager into a Serialization object.
  78489. * Returns the serialized object.
  78490. */
  78491. MorphTargetManager.prototype.serialize = function () {
  78492. var serializationObject = {};
  78493. serializationObject.id = this.uniqueId;
  78494. serializationObject.targets = [];
  78495. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78496. var target = _a[_i];
  78497. serializationObject.targets.push(target.serialize());
  78498. }
  78499. return serializationObject;
  78500. };
  78501. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  78502. var influenceCount = 0;
  78503. this._activeTargets.reset();
  78504. this._supportsNormals = true;
  78505. this._supportsTangents = true;
  78506. this._vertexCount = 0;
  78507. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78508. var target = _a[_i];
  78509. this._activeTargets.push(target);
  78510. this._tempInfluences[influenceCount++] = target.influence;
  78511. var positions = target.getPositions();
  78512. if (positions) {
  78513. this._supportsNormals = this._supportsNormals && target.hasNormals;
  78514. this._supportsTangents = this._supportsTangents && target.hasTangents;
  78515. var vertexCount = positions.length / 3;
  78516. if (this._vertexCount === 0) {
  78517. this._vertexCount = vertexCount;
  78518. }
  78519. else if (this._vertexCount !== vertexCount) {
  78520. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  78521. return;
  78522. }
  78523. }
  78524. }
  78525. if (!this._influences || this._influences.length !== influenceCount) {
  78526. this._influences = new Float32Array(influenceCount);
  78527. }
  78528. for (var index = 0; index < influenceCount; index++) {
  78529. this._influences[index] = this._tempInfluences[index];
  78530. }
  78531. if (needUpdate && this._scene) {
  78532. // Flag meshes as dirty to resync with the active targets
  78533. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  78534. var mesh = _c[_b];
  78535. if (mesh.morphTargetManager === this) {
  78536. mesh._syncGeometryWithMorphTargetManager();
  78537. }
  78538. }
  78539. }
  78540. };
  78541. // Statics
  78542. MorphTargetManager.Parse = function (serializationObject, scene) {
  78543. var result = new MorphTargetManager(scene);
  78544. result._uniqueId = serializationObject.id;
  78545. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  78546. var targetData = _a[_i];
  78547. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  78548. }
  78549. return result;
  78550. };
  78551. return MorphTargetManager;
  78552. }());
  78553. BABYLON.MorphTargetManager = MorphTargetManager;
  78554. })(BABYLON || (BABYLON = {}));
  78555. //# sourceMappingURL=babylon.morphTargetManager.js.map
  78556. var BABYLON;
  78557. (function (BABYLON) {
  78558. var Octree = /** @class */ (function () {
  78559. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  78560. if (maxDepth === void 0) { maxDepth = 2; }
  78561. this.maxDepth = maxDepth;
  78562. this.dynamicContent = new Array();
  78563. this._maxBlockCapacity = maxBlockCapacity || 64;
  78564. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  78565. this._creationFunc = creationFunc;
  78566. }
  78567. // Methods
  78568. Octree.prototype.update = function (worldMin, worldMax, entries) {
  78569. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  78570. };
  78571. Octree.prototype.addMesh = function (entry) {
  78572. for (var index = 0; index < this.blocks.length; index++) {
  78573. var block = this.blocks[index];
  78574. block.addEntry(entry);
  78575. }
  78576. };
  78577. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  78578. this._selectionContent.reset();
  78579. for (var index = 0; index < this.blocks.length; index++) {
  78580. var block = this.blocks[index];
  78581. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  78582. }
  78583. if (allowDuplicate) {
  78584. this._selectionContent.concat(this.dynamicContent);
  78585. }
  78586. else {
  78587. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78588. }
  78589. return this._selectionContent;
  78590. };
  78591. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  78592. this._selectionContent.reset();
  78593. for (var index = 0; index < this.blocks.length; index++) {
  78594. var block = this.blocks[index];
  78595. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  78596. }
  78597. if (allowDuplicate) {
  78598. this._selectionContent.concat(this.dynamicContent);
  78599. }
  78600. else {
  78601. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78602. }
  78603. return this._selectionContent;
  78604. };
  78605. Octree.prototype.intersectsRay = function (ray) {
  78606. this._selectionContent.reset();
  78607. for (var index = 0; index < this.blocks.length; index++) {
  78608. var block = this.blocks[index];
  78609. block.intersectsRay(ray, this._selectionContent);
  78610. }
  78611. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78612. return this._selectionContent;
  78613. };
  78614. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  78615. target.blocks = new Array();
  78616. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  78617. // Segmenting space
  78618. for (var x = 0; x < 2; x++) {
  78619. for (var y = 0; y < 2; y++) {
  78620. for (var z = 0; z < 2; z++) {
  78621. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  78622. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  78623. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  78624. block.addEntries(entries);
  78625. target.blocks.push(block);
  78626. }
  78627. }
  78628. }
  78629. };
  78630. Octree.CreationFuncForMeshes = function (entry, block) {
  78631. var boundingInfo = entry.getBoundingInfo();
  78632. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78633. block.entries.push(entry);
  78634. }
  78635. };
  78636. Octree.CreationFuncForSubMeshes = function (entry, block) {
  78637. var boundingInfo = entry.getBoundingInfo();
  78638. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78639. block.entries.push(entry);
  78640. }
  78641. };
  78642. return Octree;
  78643. }());
  78644. BABYLON.Octree = Octree;
  78645. })(BABYLON || (BABYLON = {}));
  78646. //# sourceMappingURL=babylon.octree.js.map
  78647. var BABYLON;
  78648. (function (BABYLON) {
  78649. var OctreeBlock = /** @class */ (function () {
  78650. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  78651. this.entries = new Array();
  78652. this._boundingVectors = new Array();
  78653. this._capacity = capacity;
  78654. this._depth = depth;
  78655. this._maxDepth = maxDepth;
  78656. this._creationFunc = creationFunc;
  78657. this._minPoint = minPoint;
  78658. this._maxPoint = maxPoint;
  78659. this._boundingVectors.push(minPoint.clone());
  78660. this._boundingVectors.push(maxPoint.clone());
  78661. this._boundingVectors.push(minPoint.clone());
  78662. this._boundingVectors[2].x = maxPoint.x;
  78663. this._boundingVectors.push(minPoint.clone());
  78664. this._boundingVectors[3].y = maxPoint.y;
  78665. this._boundingVectors.push(minPoint.clone());
  78666. this._boundingVectors[4].z = maxPoint.z;
  78667. this._boundingVectors.push(maxPoint.clone());
  78668. this._boundingVectors[5].z = minPoint.z;
  78669. this._boundingVectors.push(maxPoint.clone());
  78670. this._boundingVectors[6].x = minPoint.x;
  78671. this._boundingVectors.push(maxPoint.clone());
  78672. this._boundingVectors[7].y = minPoint.y;
  78673. }
  78674. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  78675. // Property
  78676. get: function () {
  78677. return this._capacity;
  78678. },
  78679. enumerable: true,
  78680. configurable: true
  78681. });
  78682. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  78683. get: function () {
  78684. return this._minPoint;
  78685. },
  78686. enumerable: true,
  78687. configurable: true
  78688. });
  78689. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  78690. get: function () {
  78691. return this._maxPoint;
  78692. },
  78693. enumerable: true,
  78694. configurable: true
  78695. });
  78696. // Methods
  78697. OctreeBlock.prototype.addEntry = function (entry) {
  78698. if (this.blocks) {
  78699. for (var index = 0; index < this.blocks.length; index++) {
  78700. var block = this.blocks[index];
  78701. block.addEntry(entry);
  78702. }
  78703. return;
  78704. }
  78705. this._creationFunc(entry, this);
  78706. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  78707. this.createInnerBlocks();
  78708. }
  78709. };
  78710. OctreeBlock.prototype.addEntries = function (entries) {
  78711. for (var index = 0; index < entries.length; index++) {
  78712. var mesh = entries[index];
  78713. this.addEntry(mesh);
  78714. }
  78715. };
  78716. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  78717. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  78718. if (this.blocks) {
  78719. for (var index = 0; index < this.blocks.length; index++) {
  78720. var block = this.blocks[index];
  78721. block.select(frustumPlanes, selection, allowDuplicate);
  78722. }
  78723. return;
  78724. }
  78725. if (allowDuplicate) {
  78726. selection.concat(this.entries);
  78727. }
  78728. else {
  78729. selection.concatWithNoDuplicate(this.entries);
  78730. }
  78731. }
  78732. };
  78733. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  78734. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  78735. if (this.blocks) {
  78736. for (var index = 0; index < this.blocks.length; index++) {
  78737. var block = this.blocks[index];
  78738. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  78739. }
  78740. return;
  78741. }
  78742. if (allowDuplicate) {
  78743. selection.concat(this.entries);
  78744. }
  78745. else {
  78746. selection.concatWithNoDuplicate(this.entries);
  78747. }
  78748. }
  78749. };
  78750. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  78751. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  78752. if (this.blocks) {
  78753. for (var index = 0; index < this.blocks.length; index++) {
  78754. var block = this.blocks[index];
  78755. block.intersectsRay(ray, selection);
  78756. }
  78757. return;
  78758. }
  78759. selection.concatWithNoDuplicate(this.entries);
  78760. }
  78761. };
  78762. OctreeBlock.prototype.createInnerBlocks = function () {
  78763. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  78764. };
  78765. return OctreeBlock;
  78766. }());
  78767. BABYLON.OctreeBlock = OctreeBlock;
  78768. })(BABYLON || (BABYLON = {}));
  78769. //# sourceMappingURL=babylon.octreeBlock.js.map
  78770. var BABYLON;
  78771. (function (BABYLON) {
  78772. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  78773. __extends(VRDistortionCorrectionPostProcess, _super);
  78774. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  78775. var _this = _super.call(this, name, "vrDistortionCorrection", [
  78776. 'LensCenter',
  78777. 'Scale',
  78778. 'ScaleIn',
  78779. 'HmdWarpParam'
  78780. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  78781. _this._isRightEye = isRightEye;
  78782. _this._distortionFactors = vrMetrics.distortionK;
  78783. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  78784. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  78785. _this.adaptScaleToCurrentViewport = true;
  78786. _this.onSizeChangedObservable.add(function () {
  78787. _this.aspectRatio = _this.width * .5 / _this.height;
  78788. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  78789. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  78790. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  78791. });
  78792. _this.onApplyObservable.add(function (effect) {
  78793. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  78794. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  78795. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  78796. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  78797. });
  78798. return _this;
  78799. }
  78800. return VRDistortionCorrectionPostProcess;
  78801. }(BABYLON.PostProcess));
  78802. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  78803. })(BABYLON || (BABYLON = {}));
  78804. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  78805. var BABYLON;
  78806. (function (BABYLON) {
  78807. var AnaglyphPostProcess = /** @class */ (function (_super) {
  78808. __extends(AnaglyphPostProcess, _super);
  78809. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  78810. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  78811. _this._passedProcess = rigCameras[0]._rigPostProcess;
  78812. _this.onApplyObservable.add(function (effect) {
  78813. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  78814. });
  78815. return _this;
  78816. }
  78817. return AnaglyphPostProcess;
  78818. }(BABYLON.PostProcess));
  78819. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  78820. })(BABYLON || (BABYLON = {}));
  78821. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  78822. var BABYLON;
  78823. (function (BABYLON) {
  78824. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  78825. __extends(StereoscopicInterlacePostProcess, _super);
  78826. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  78827. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  78828. _this._passedProcess = rigCameras[0]._rigPostProcess;
  78829. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  78830. _this.onSizeChangedObservable.add(function () {
  78831. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  78832. });
  78833. _this.onApplyObservable.add(function (effect) {
  78834. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  78835. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  78836. });
  78837. return _this;
  78838. }
  78839. return StereoscopicInterlacePostProcess;
  78840. }(BABYLON.PostProcess));
  78841. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  78842. })(BABYLON || (BABYLON = {}));
  78843. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  78844. var BABYLON;
  78845. (function (BABYLON) {
  78846. /**
  78847. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  78848. * Screen rotation is taken into account.
  78849. */
  78850. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  78851. function FreeCameraDeviceOrientationInput() {
  78852. var _this = this;
  78853. this._screenOrientationAngle = 0;
  78854. this._screenQuaternion = new BABYLON.Quaternion();
  78855. this._alpha = 0;
  78856. this._beta = 0;
  78857. this._gamma = 0;
  78858. this._orientationChanged = function () {
  78859. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  78860. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  78861. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  78862. };
  78863. this._deviceOrientation = function (evt) {
  78864. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  78865. _this._beta = evt.beta !== null ? evt.beta : 0;
  78866. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  78867. };
  78868. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  78869. this._orientationChanged();
  78870. }
  78871. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  78872. get: function () {
  78873. return this._camera;
  78874. },
  78875. set: function (camera) {
  78876. this._camera = camera;
  78877. if (this._camera != null && !this._camera.rotationQuaternion) {
  78878. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  78879. }
  78880. },
  78881. enumerable: true,
  78882. configurable: true
  78883. });
  78884. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  78885. window.addEventListener("orientationchange", this._orientationChanged);
  78886. window.addEventListener("deviceorientation", this._deviceOrientation);
  78887. //In certain cases, the attach control is called AFTER orientation was changed,
  78888. //So this is needed.
  78889. this._orientationChanged();
  78890. };
  78891. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  78892. window.removeEventListener("orientationchange", this._orientationChanged);
  78893. window.removeEventListener("deviceorientation", this._deviceOrientation);
  78894. };
  78895. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  78896. //if no device orientation provided, don't update the rotation.
  78897. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  78898. if (!this._alpha)
  78899. return;
  78900. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  78901. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  78902. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  78903. //Mirror on XY Plane
  78904. this._camera.rotationQuaternion.z *= -1;
  78905. this._camera.rotationQuaternion.w *= -1;
  78906. };
  78907. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  78908. return "FreeCameraDeviceOrientationInput";
  78909. };
  78910. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  78911. return "deviceOrientation";
  78912. };
  78913. return FreeCameraDeviceOrientationInput;
  78914. }());
  78915. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  78916. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  78917. })(BABYLON || (BABYLON = {}));
  78918. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  78919. var BABYLON;
  78920. (function (BABYLON) {
  78921. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  78922. function ArcRotateCameraVRDeviceOrientationInput() {
  78923. this.alphaCorrection = 1;
  78924. this.betaCorrection = 1;
  78925. this.gammaCorrection = 1;
  78926. this._alpha = 0;
  78927. this._gamma = 0;
  78928. this._dirty = false;
  78929. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  78930. }
  78931. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  78932. this.camera.attachControl(element, noPreventDefault);
  78933. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  78934. };
  78935. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  78936. if (evt.alpha !== null) {
  78937. this._alpha = +evt.alpha | 0;
  78938. }
  78939. if (evt.gamma !== null) {
  78940. this._gamma = +evt.gamma | 0;
  78941. }
  78942. this._dirty = true;
  78943. };
  78944. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  78945. if (this._dirty) {
  78946. this._dirty = false;
  78947. if (this._gamma < 0) {
  78948. this._gamma = 180 + this._gamma;
  78949. }
  78950. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  78951. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  78952. }
  78953. };
  78954. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  78955. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  78956. };
  78957. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  78958. return "ArcRotateCameraVRDeviceOrientationInput";
  78959. };
  78960. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  78961. return "VRDeviceOrientation";
  78962. };
  78963. return ArcRotateCameraVRDeviceOrientationInput;
  78964. }());
  78965. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  78966. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  78967. })(BABYLON || (BABYLON = {}));
  78968. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  78969. var BABYLON;
  78970. (function (BABYLON) {
  78971. var VRCameraMetrics = /** @class */ (function () {
  78972. function VRCameraMetrics() {
  78973. this.compensateDistortion = true;
  78974. }
  78975. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  78976. get: function () {
  78977. return this.hResolution / (2 * this.vResolution);
  78978. },
  78979. enumerable: true,
  78980. configurable: true
  78981. });
  78982. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  78983. get: function () {
  78984. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  78985. },
  78986. enumerable: true,
  78987. configurable: true
  78988. });
  78989. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  78990. get: function () {
  78991. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  78992. var h = (4 * meters) / this.hScreenSize;
  78993. return BABYLON.Matrix.Translation(h, 0, 0);
  78994. },
  78995. enumerable: true,
  78996. configurable: true
  78997. });
  78998. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  78999. get: function () {
  79000. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79001. var h = (4 * meters) / this.hScreenSize;
  79002. return BABYLON.Matrix.Translation(-h, 0, 0);
  79003. },
  79004. enumerable: true,
  79005. configurable: true
  79006. });
  79007. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  79008. get: function () {
  79009. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  79010. },
  79011. enumerable: true,
  79012. configurable: true
  79013. });
  79014. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  79015. get: function () {
  79016. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  79017. },
  79018. enumerable: true,
  79019. configurable: true
  79020. });
  79021. VRCameraMetrics.GetDefault = function () {
  79022. var result = new VRCameraMetrics();
  79023. result.hResolution = 1280;
  79024. result.vResolution = 800;
  79025. result.hScreenSize = 0.149759993;
  79026. result.vScreenSize = 0.0935999975;
  79027. result.vScreenCenter = 0.0467999987;
  79028. result.eyeToScreenDistance = 0.0410000011;
  79029. result.lensSeparationDistance = 0.0635000020;
  79030. result.interpupillaryDistance = 0.0640000030;
  79031. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  79032. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  79033. result.postProcessScaleFactor = 1.714605507808412;
  79034. result.lensCenterOffset = 0.151976421;
  79035. return result;
  79036. };
  79037. return VRCameraMetrics;
  79038. }());
  79039. BABYLON.VRCameraMetrics = VRCameraMetrics;
  79040. })(BABYLON || (BABYLON = {}));
  79041. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  79042. var BABYLON;
  79043. (function (BABYLON) {
  79044. /**
  79045. * This represents a WebVR camera.
  79046. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  79047. * @example http://doc.babylonjs.com/how_to/webvr_camera
  79048. */
  79049. var WebVRFreeCamera = /** @class */ (function (_super) {
  79050. __extends(WebVRFreeCamera, _super);
  79051. /**
  79052. * Instantiates a WebVRFreeCamera.
  79053. * @param name The name of the WebVRFreeCamera
  79054. * @param position The starting anchor position for the camera
  79055. * @param scene The scene the camera belongs to
  79056. * @param webVROptions a set of customizable options for the webVRCamera
  79057. */
  79058. function WebVRFreeCamera(name, position, scene, webVROptions) {
  79059. if (webVROptions === void 0) { webVROptions = {}; }
  79060. var _this = _super.call(this, name, position, scene) || this;
  79061. _this.webVROptions = webVROptions;
  79062. /**
  79063. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  79064. */
  79065. _this._vrDevice = null;
  79066. /**
  79067. * The rawPose of the vrDevice.
  79068. */
  79069. _this.rawPose = null;
  79070. _this._specsVersion = "1.1";
  79071. _this._attached = false;
  79072. _this._descendants = [];
  79073. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79074. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79075. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  79076. _this._standingMatrix = null;
  79077. /**
  79078. * Represents device position in babylon space.
  79079. */
  79080. _this.devicePosition = BABYLON.Vector3.Zero();
  79081. /**
  79082. * Represents device rotation in babylon space.
  79083. */
  79084. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  79085. /**
  79086. * The scale of the device to be used when translating from device space to babylon space.
  79087. */
  79088. _this.deviceScaleFactor = 1;
  79089. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79090. _this._worldToDevice = BABYLON.Matrix.Identity();
  79091. /**
  79092. * References to the webVR controllers for the vrDevice.
  79093. */
  79094. _this.controllers = [];
  79095. /**
  79096. * Emits an event when a controller is attached.
  79097. */
  79098. _this.onControllersAttachedObservable = new BABYLON.Observable();
  79099. /**
  79100. * Emits an event when a controller's mesh has been loaded;
  79101. */
  79102. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79103. /**
  79104. * If the rig cameras be used as parent instead of this camera.
  79105. */
  79106. _this.rigParenting = true;
  79107. _this._defaultHeight = undefined;
  79108. _this._workingVector = BABYLON.Vector3.Zero();
  79109. _this._oneVector = BABYLON.Vector3.One();
  79110. _this._workingMatrix = BABYLON.Matrix.Identity();
  79111. _this._cache.position = BABYLON.Vector3.Zero();
  79112. if (webVROptions.defaultHeight) {
  79113. _this._defaultHeight = webVROptions.defaultHeight;
  79114. _this.position.y = _this._defaultHeight;
  79115. }
  79116. _this.minZ = 0.1;
  79117. //legacy support - the compensation boolean was removed.
  79118. if (arguments.length === 5) {
  79119. _this.webVROptions = arguments[4];
  79120. }
  79121. // default webVR options
  79122. if (_this.webVROptions.trackPosition == undefined) {
  79123. _this.webVROptions.trackPosition = true;
  79124. }
  79125. if (_this.webVROptions.controllerMeshes == undefined) {
  79126. _this.webVROptions.controllerMeshes = true;
  79127. }
  79128. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  79129. _this.webVROptions.defaultLightingOnControllers = true;
  79130. }
  79131. _this.rotationQuaternion = new BABYLON.Quaternion();
  79132. if (_this.webVROptions && _this.webVROptions.positionScale) {
  79133. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  79134. }
  79135. //enable VR
  79136. var engine = _this.getEngine();
  79137. _this._onVREnabled = function (success) { if (success) {
  79138. _this.initControllers();
  79139. } };
  79140. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  79141. engine.initWebVR().add(function (event) {
  79142. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  79143. return;
  79144. }
  79145. _this._vrDevice = event.vrDisplay;
  79146. //reset the rig parameters.
  79147. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  79148. if (_this._attached) {
  79149. _this.getEngine().enableVR();
  79150. }
  79151. });
  79152. if (typeof (VRFrameData) !== "undefined")
  79153. _this._frameData = new VRFrameData();
  79154. /**
  79155. * The idea behind the following lines:
  79156. * objects that have the camera as parent should actually have the rig cameras as a parent.
  79157. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  79158. * the second will not show it correctly.
  79159. *
  79160. * To solve this - each object that has the camera as parent will be added to a protected array.
  79161. * When the rig camera renders, it will take this array and set all of those to be its children.
  79162. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  79163. * Amazing!
  79164. */
  79165. scene.onBeforeCameraRenderObservable.add(function (camera) {
  79166. if (camera.parent === _this && _this.rigParenting) {
  79167. _this._descendants = _this.getDescendants(true, function (n) {
  79168. // don't take the cameras or the controllers!
  79169. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  79170. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  79171. return !isController && !isRigCamera;
  79172. });
  79173. _this._descendants.forEach(function (node) {
  79174. node.parent = camera;
  79175. });
  79176. }
  79177. });
  79178. scene.onAfterCameraRenderObservable.add(function (camera) {
  79179. if (camera.parent === _this && _this.rigParenting) {
  79180. _this._descendants.forEach(function (node) {
  79181. node.parent = _this;
  79182. });
  79183. }
  79184. });
  79185. return _this;
  79186. }
  79187. /**
  79188. * Gets the device distance from the ground in meters.
  79189. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  79190. */
  79191. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  79192. if (this._standingMatrix) {
  79193. // Add standing matrix offset to get real offset from ground in room
  79194. this._standingMatrix.getTranslationToRef(this._workingVector);
  79195. return this._deviceRoomPosition.y + this._workingVector.y;
  79196. }
  79197. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  79198. return this._defaultHeight || 0;
  79199. };
  79200. /**
  79201. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79202. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  79203. */
  79204. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  79205. var _this = this;
  79206. if (callback === void 0) { callback = function (bool) { }; }
  79207. // Use standing matrix if available
  79208. this.getEngine().initWebVRAsync().then(function (result) {
  79209. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  79210. callback(false);
  79211. }
  79212. else {
  79213. _this._standingMatrix = new BABYLON.Matrix();
  79214. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  79215. if (!_this.getScene().useRightHandedSystem) {
  79216. [2, 6, 8, 9, 14].forEach(function (num) {
  79217. if (_this._standingMatrix) {
  79218. _this._standingMatrix.m[num] *= -1;
  79219. }
  79220. });
  79221. }
  79222. callback(true);
  79223. }
  79224. });
  79225. };
  79226. /**
  79227. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79228. * @returns A promise with a boolean set to if the standing matrix is supported.
  79229. */
  79230. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  79231. var _this = this;
  79232. return new Promise(function (res, rej) {
  79233. _this.useStandingMatrix(function (supported) {
  79234. res(supported);
  79235. });
  79236. });
  79237. };
  79238. /**
  79239. * Disposes the camera
  79240. */
  79241. WebVRFreeCamera.prototype.dispose = function () {
  79242. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  79243. _super.prototype.dispose.call(this);
  79244. };
  79245. /**
  79246. * Gets a vrController by name.
  79247. * @param name The name of the controller to retreive
  79248. * @returns the controller matching the name specified or null if not found
  79249. */
  79250. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  79251. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  79252. var gp = _a[_i];
  79253. if (gp.hand === name) {
  79254. return gp;
  79255. }
  79256. }
  79257. return null;
  79258. };
  79259. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  79260. /**
  79261. * The controller corrisponding to the users left hand.
  79262. */
  79263. get: function () {
  79264. if (!this._leftController) {
  79265. this._leftController = this.getControllerByName("left");
  79266. }
  79267. return this._leftController;
  79268. },
  79269. enumerable: true,
  79270. configurable: true
  79271. });
  79272. ;
  79273. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  79274. /**
  79275. * The controller corrisponding to the users right hand.
  79276. */
  79277. get: function () {
  79278. if (!this._rightController) {
  79279. this._rightController = this.getControllerByName("right");
  79280. }
  79281. return this._rightController;
  79282. },
  79283. enumerable: true,
  79284. configurable: true
  79285. });
  79286. ;
  79287. /**
  79288. * Casts a ray forward from the vrCamera's gaze.
  79289. * @param length Length of the ray (default: 100)
  79290. * @returns the ray corrisponding to the gaze
  79291. */
  79292. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  79293. if (length === void 0) { length = 100; }
  79294. if (this.leftCamera) {
  79295. // Use left eye to avoid computation to compute center on every call
  79296. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  79297. }
  79298. else {
  79299. return _super.prototype.getForwardRay.call(this, length);
  79300. }
  79301. };
  79302. /**
  79303. * Updates the camera based on device's frame data
  79304. */
  79305. WebVRFreeCamera.prototype._checkInputs = function () {
  79306. if (this._vrDevice && this._vrDevice.isPresenting) {
  79307. this._vrDevice.getFrameData(this._frameData);
  79308. this.updateFromDevice(this._frameData.pose);
  79309. }
  79310. _super.prototype._checkInputs.call(this);
  79311. };
  79312. /**
  79313. * Updates the poseControlled values based on the input device pose.
  79314. * @param poseData Pose coming from the device
  79315. */
  79316. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  79317. if (poseData && poseData.orientation) {
  79318. this.rawPose = poseData;
  79319. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  79320. if (this.getScene().useRightHandedSystem) {
  79321. this._deviceRoomRotationQuaternion.z *= -1;
  79322. this._deviceRoomRotationQuaternion.w *= -1;
  79323. }
  79324. if (this.webVROptions.trackPosition && this.rawPose.position) {
  79325. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  79326. if (this.getScene().useRightHandedSystem) {
  79327. this._deviceRoomPosition.z *= -1;
  79328. }
  79329. }
  79330. }
  79331. };
  79332. /**
  79333. * WebVR's attach control will start broadcasting frames to the device.
  79334. * Note that in certain browsers (chrome for example) this function must be called
  79335. * within a user-interaction callback. Example:
  79336. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  79337. *
  79338. * @param element html element to attach the vrDevice to
  79339. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  79340. */
  79341. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  79342. _super.prototype.attachControl.call(this, element, noPreventDefault);
  79343. this._attached = true;
  79344. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  79345. if (this._vrDevice) {
  79346. this.getEngine().enableVR();
  79347. }
  79348. };
  79349. /**
  79350. * Detaches the camera from the html element and disables VR
  79351. *
  79352. * @param element html element to detach from
  79353. */
  79354. WebVRFreeCamera.prototype.detachControl = function (element) {
  79355. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79356. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79357. _super.prototype.detachControl.call(this, element);
  79358. this._attached = false;
  79359. this.getEngine().disableVR();
  79360. };
  79361. /**
  79362. * @returns the name of this class
  79363. */
  79364. WebVRFreeCamera.prototype.getClassName = function () {
  79365. return "WebVRFreeCamera";
  79366. };
  79367. /**
  79368. * Calls resetPose on the vrDisplay
  79369. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  79370. */
  79371. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  79372. //uses the vrDisplay's "resetPose()".
  79373. //pitch and roll won't be affected.
  79374. this._vrDevice.resetPose();
  79375. };
  79376. /**
  79377. * Updates the rig cameras (left and right eye)
  79378. */
  79379. WebVRFreeCamera.prototype._updateRigCameras = function () {
  79380. var camLeft = this._rigCameras[0];
  79381. var camRight = this._rigCameras[1];
  79382. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79383. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79384. camLeft.position.copyFrom(this._deviceRoomPosition);
  79385. camRight.position.copyFrom(this._deviceRoomPosition);
  79386. };
  79387. /**
  79388. * Updates the cached values of the camera
  79389. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  79390. */
  79391. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  79392. var _this = this;
  79393. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  79394. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  79395. if (!this.updateCacheCalled) {
  79396. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  79397. this.updateCacheCalled = true;
  79398. this.update();
  79399. }
  79400. // Set working vector to the device position in room space rotated by the new rotation
  79401. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  79402. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  79403. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  79404. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  79405. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  79406. // Add translation from anchor position
  79407. this._deviceToWorld.getTranslationToRef(this._workingVector);
  79408. this._workingVector.addInPlace(this.position);
  79409. this._workingVector.subtractInPlace(this._cache.position);
  79410. this._deviceToWorld.setTranslation(this._workingVector);
  79411. // Set an inverted matrix to be used when updating the camera
  79412. this._deviceToWorld.invertToRef(this._worldToDevice);
  79413. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  79414. this.controllers.forEach(function (controller) {
  79415. controller._deviceToWorld = _this._deviceToWorld;
  79416. controller.update();
  79417. });
  79418. }
  79419. if (!ignoreParentClass) {
  79420. _super.prototype._updateCache.call(this);
  79421. }
  79422. this.updateCacheCalled = false;
  79423. };
  79424. /**
  79425. * Updates the current device position and rotation in the babylon world
  79426. */
  79427. WebVRFreeCamera.prototype.update = function () {
  79428. // Get current device position in babylon world
  79429. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  79430. // Get current device rotation in babylon world
  79431. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  79432. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  79433. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  79434. _super.prototype.update.call(this);
  79435. };
  79436. /**
  79437. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  79438. * @returns an identity matrix
  79439. */
  79440. WebVRFreeCamera.prototype._getViewMatrix = function () {
  79441. return BABYLON.Matrix.Identity();
  79442. };
  79443. /**
  79444. * This function is called by the two RIG cameras.
  79445. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  79446. */
  79447. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  79448. var _this = this;
  79449. //WebVR 1.1
  79450. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  79451. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  79452. if (!this.getScene().useRightHandedSystem) {
  79453. [2, 6, 8, 9, 14].forEach(function (num) {
  79454. _this._webvrViewMatrix.m[num] *= -1;
  79455. });
  79456. }
  79457. // update the camera rotation matrix
  79458. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  79459. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  79460. // Computing target and final matrix
  79461. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  79462. var parentCamera = this._cameraRigParams["parentCamera"];
  79463. // should the view matrix be updated with scale and position offset?
  79464. if (parentCamera.deviceScaleFactor !== 1) {
  79465. this._webvrViewMatrix.invert();
  79466. // scale the position, if set
  79467. if (parentCamera.deviceScaleFactor) {
  79468. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  79469. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  79470. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  79471. }
  79472. this._webvrViewMatrix.invert();
  79473. }
  79474. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  79475. return this._webvrViewMatrix;
  79476. };
  79477. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  79478. var _this = this;
  79479. var parentCamera = this.parent;
  79480. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  79481. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  79482. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  79483. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  79484. //babylon compatible matrix
  79485. if (!this.getScene().useRightHandedSystem) {
  79486. [8, 9, 10, 11].forEach(function (num) {
  79487. _this._projectionMatrix.m[num] *= -1;
  79488. });
  79489. }
  79490. return this._projectionMatrix;
  79491. };
  79492. /**
  79493. * Initializes the controllers and their meshes
  79494. */
  79495. WebVRFreeCamera.prototype.initControllers = function () {
  79496. var _this = this;
  79497. this.controllers = [];
  79498. var manager = this.getScene().gamepadManager;
  79499. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79500. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79501. var webVrController = gamepad;
  79502. if (webVrController.defaultModel) {
  79503. webVrController.defaultModel.setEnabled(false);
  79504. }
  79505. if (webVrController.hand === "right") {
  79506. _this._rightController = null;
  79507. }
  79508. if (webVrController.hand === "left") {
  79509. _this._rightController = null;
  79510. }
  79511. var controllerIndex = _this.controllers.indexOf(webVrController);
  79512. if (controllerIndex !== -1) {
  79513. _this.controllers.splice(controllerIndex, 1);
  79514. }
  79515. }
  79516. });
  79517. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79518. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79519. var webVrController_1 = gamepad;
  79520. webVrController_1._deviceToWorld = _this._deviceToWorld;
  79521. if (_this.webVROptions.controllerMeshes) {
  79522. if (webVrController_1.defaultModel) {
  79523. webVrController_1.defaultModel.setEnabled(true);
  79524. }
  79525. else {
  79526. // Load the meshes
  79527. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  79528. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  79529. if (_this.webVROptions.defaultLightingOnControllers) {
  79530. if (!_this._lightOnControllers) {
  79531. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  79532. }
  79533. var activateLightOnSubMeshes_1 = function (mesh, light) {
  79534. var children = mesh.getChildren();
  79535. if (children.length !== 0) {
  79536. children.forEach(function (mesh) {
  79537. light.includedOnlyMeshes.push(mesh);
  79538. activateLightOnSubMeshes_1(mesh, light);
  79539. });
  79540. }
  79541. };
  79542. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  79543. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  79544. }
  79545. });
  79546. }
  79547. }
  79548. webVrController_1.attachToPoseControlledCamera(_this);
  79549. // since this is async - sanity check. Is the controller already stored?
  79550. if (_this.controllers.indexOf(webVrController_1) === -1) {
  79551. //add to the controllers array
  79552. _this.controllers.push(webVrController_1);
  79553. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  79554. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  79555. // So we're overriding setting left & right manually to be sure
  79556. var firstViveWandDetected = false;
  79557. for (var i = 0; i < _this.controllers.length; i++) {
  79558. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79559. if (!firstViveWandDetected) {
  79560. firstViveWandDetected = true;
  79561. _this.controllers[i].hand = "left";
  79562. }
  79563. else {
  79564. _this.controllers[i].hand = "right";
  79565. }
  79566. }
  79567. }
  79568. //did we find enough controllers? Great! let the developer know.
  79569. if (_this.controllers.length >= 2) {
  79570. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  79571. }
  79572. }
  79573. }
  79574. });
  79575. };
  79576. return WebVRFreeCamera;
  79577. }(BABYLON.FreeCamera));
  79578. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  79579. })(BABYLON || (BABYLON = {}));
  79580. //# sourceMappingURL=babylon.webVRCamera.js.map
  79581. var BABYLON;
  79582. (function (BABYLON) {
  79583. // We're mainly based on the logic defined into the FreeCamera code
  79584. /**
  79585. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  79586. * being tilted forward or back and left or right.
  79587. */
  79588. var DeviceOrientationCamera = /** @class */ (function (_super) {
  79589. __extends(DeviceOrientationCamera, _super);
  79590. /**
  79591. * Creates a new device orientation camera. @see DeviceOrientationCamera
  79592. * @param name The name of the camera
  79593. * @param position The start position camera
  79594. * @param scene The scene the camera belongs to
  79595. */
  79596. function DeviceOrientationCamera(name, position, scene) {
  79597. var _this = _super.call(this, name, position, scene) || this;
  79598. _this._quaternionCache = new BABYLON.Quaternion();
  79599. _this.inputs.addDeviceOrientation();
  79600. return _this;
  79601. }
  79602. /**
  79603. * Gets the current instance class name ("DeviceOrientationCamera").
  79604. * This helps avoiding instanceof at run time.
  79605. * @returns the class name
  79606. */
  79607. DeviceOrientationCamera.prototype.getClassName = function () {
  79608. return "DeviceOrientationCamera";
  79609. };
  79610. /**
  79611. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  79612. */
  79613. DeviceOrientationCamera.prototype._checkInputs = function () {
  79614. _super.prototype._checkInputs.call(this);
  79615. this._quaternionCache.copyFrom(this.rotationQuaternion);
  79616. if (this._initialQuaternion) {
  79617. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79618. }
  79619. };
  79620. /**
  79621. * Reset the camera to its default orientation on the specified axis only.
  79622. * @param axis The axis to reset
  79623. */
  79624. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  79625. var _this = this;
  79626. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  79627. //can only work if this camera has a rotation quaternion already.
  79628. if (!this.rotationQuaternion)
  79629. return;
  79630. if (!this._initialQuaternion) {
  79631. this._initialQuaternion = new BABYLON.Quaternion();
  79632. }
  79633. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  79634. ['x', 'y', 'z'].forEach(function (axisName) {
  79635. if (!axis[axisName]) {
  79636. _this._initialQuaternion[axisName] = 0;
  79637. }
  79638. else {
  79639. _this._initialQuaternion[axisName] *= -1;
  79640. }
  79641. });
  79642. this._initialQuaternion.normalize();
  79643. //force rotation update
  79644. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79645. };
  79646. return DeviceOrientationCamera;
  79647. }(BABYLON.FreeCamera));
  79648. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  79649. })(BABYLON || (BABYLON = {}));
  79650. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  79651. var BABYLON;
  79652. (function (BABYLON) {
  79653. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  79654. __extends(VRDeviceOrientationFreeCamera, _super);
  79655. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79656. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79657. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79658. var _this = _super.call(this, name, position, scene) || this;
  79659. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79660. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79661. return _this;
  79662. }
  79663. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  79664. return "VRDeviceOrientationFreeCamera";
  79665. };
  79666. return VRDeviceOrientationFreeCamera;
  79667. }(BABYLON.DeviceOrientationCamera));
  79668. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  79669. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  79670. __extends(VRDeviceOrientationGamepadCamera, _super);
  79671. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79672. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79673. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79674. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  79675. _this.inputs.addGamepad();
  79676. return _this;
  79677. }
  79678. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  79679. return "VRDeviceOrientationGamepadCamera";
  79680. };
  79681. return VRDeviceOrientationGamepadCamera;
  79682. }(VRDeviceOrientationFreeCamera));
  79683. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  79684. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  79685. __extends(VRDeviceOrientationArcRotateCamera, _super);
  79686. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  79687. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79688. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79689. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79690. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79691. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79692. _this.inputs.addVRDeviceOrientation();
  79693. return _this;
  79694. }
  79695. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  79696. return "VRDeviceOrientationArcRotateCamera";
  79697. };
  79698. return VRDeviceOrientationArcRotateCamera;
  79699. }(BABYLON.ArcRotateCamera));
  79700. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  79701. })(BABYLON || (BABYLON = {}));
  79702. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  79703. var BABYLON;
  79704. (function (BABYLON) {
  79705. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  79706. __extends(AnaglyphFreeCamera, _super);
  79707. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  79708. var _this = _super.call(this, name, position, scene) || this;
  79709. _this.interaxialDistance = interaxialDistance;
  79710. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79711. return _this;
  79712. }
  79713. AnaglyphFreeCamera.prototype.getClassName = function () {
  79714. return "AnaglyphFreeCamera";
  79715. };
  79716. return AnaglyphFreeCamera;
  79717. }(BABYLON.FreeCamera));
  79718. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  79719. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  79720. __extends(AnaglyphArcRotateCamera, _super);
  79721. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  79722. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79723. _this.interaxialDistance = interaxialDistance;
  79724. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79725. return _this;
  79726. }
  79727. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  79728. return "AnaglyphArcRotateCamera";
  79729. };
  79730. return AnaglyphArcRotateCamera;
  79731. }(BABYLON.ArcRotateCamera));
  79732. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  79733. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  79734. __extends(AnaglyphGamepadCamera, _super);
  79735. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  79736. var _this = _super.call(this, name, position, scene) || this;
  79737. _this.interaxialDistance = interaxialDistance;
  79738. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79739. return _this;
  79740. }
  79741. AnaglyphGamepadCamera.prototype.getClassName = function () {
  79742. return "AnaglyphGamepadCamera";
  79743. };
  79744. return AnaglyphGamepadCamera;
  79745. }(BABYLON.GamepadCamera));
  79746. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  79747. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  79748. __extends(AnaglyphUniversalCamera, _super);
  79749. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  79750. var _this = _super.call(this, name, position, scene) || this;
  79751. _this.interaxialDistance = interaxialDistance;
  79752. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79753. return _this;
  79754. }
  79755. AnaglyphUniversalCamera.prototype.getClassName = function () {
  79756. return "AnaglyphUniversalCamera";
  79757. };
  79758. return AnaglyphUniversalCamera;
  79759. }(BABYLON.UniversalCamera));
  79760. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  79761. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  79762. __extends(StereoscopicFreeCamera, _super);
  79763. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79764. var _this = _super.call(this, name, position, scene) || this;
  79765. _this.interaxialDistance = interaxialDistance;
  79766. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79767. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79768. return _this;
  79769. }
  79770. StereoscopicFreeCamera.prototype.getClassName = function () {
  79771. return "StereoscopicFreeCamera";
  79772. };
  79773. return StereoscopicFreeCamera;
  79774. }(BABYLON.FreeCamera));
  79775. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  79776. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  79777. __extends(StereoscopicArcRotateCamera, _super);
  79778. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  79779. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79780. _this.interaxialDistance = interaxialDistance;
  79781. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79782. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79783. return _this;
  79784. }
  79785. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  79786. return "StereoscopicArcRotateCamera";
  79787. };
  79788. return StereoscopicArcRotateCamera;
  79789. }(BABYLON.ArcRotateCamera));
  79790. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  79791. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  79792. __extends(StereoscopicGamepadCamera, _super);
  79793. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79794. var _this = _super.call(this, name, position, scene) || this;
  79795. _this.interaxialDistance = interaxialDistance;
  79796. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79797. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79798. return _this;
  79799. }
  79800. StereoscopicGamepadCamera.prototype.getClassName = function () {
  79801. return "StereoscopicGamepadCamera";
  79802. };
  79803. return StereoscopicGamepadCamera;
  79804. }(BABYLON.GamepadCamera));
  79805. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  79806. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  79807. __extends(StereoscopicUniversalCamera, _super);
  79808. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79809. var _this = _super.call(this, name, position, scene) || this;
  79810. _this.interaxialDistance = interaxialDistance;
  79811. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79812. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79813. return _this;
  79814. }
  79815. StereoscopicUniversalCamera.prototype.getClassName = function () {
  79816. return "StereoscopicUniversalCamera";
  79817. };
  79818. return StereoscopicUniversalCamera;
  79819. }(BABYLON.UniversalCamera));
  79820. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  79821. })(BABYLON || (BABYLON = {}));
  79822. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  79823. var BABYLON;
  79824. (function (BABYLON) {
  79825. /**
  79826. * Helps to quickly add VR support to an existing scene.
  79827. * See http://doc.babylonjs.com/how_to/webvr_helper
  79828. */
  79829. var VRExperienceHelper = /** @class */ (function () {
  79830. /**
  79831. * Instantiates a VRExperienceHelper.
  79832. * Helps to quickly add VR support to an existing scene.
  79833. * @param scene The scene the VRExperienceHelper belongs to.
  79834. * @param webVROptions Options to modify the vr experience helper's behavior.
  79835. */
  79836. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  79837. if (webVROptions === void 0) { webVROptions = {}; }
  79838. var _this = this;
  79839. this.webVROptions = webVROptions;
  79840. // Can the system support WebVR, even if a headset isn't plugged in?
  79841. this._webVRsupported = false;
  79842. // If WebVR is supported, is a headset plugged in and are we ready to present?
  79843. this._webVRready = false;
  79844. // Are we waiting for the requestPresent callback to complete?
  79845. this._webVRrequesting = false;
  79846. // Are we presenting to the headset right now?
  79847. this._webVRpresenting = false;
  79848. // Are we presenting in the fullscreen fallback?
  79849. this._fullscreenVRpresenting = false;
  79850. /**
  79851. * Observable raised when entering VR.
  79852. */
  79853. this.onEnteringVRObservable = new BABYLON.Observable();
  79854. /**
  79855. * Observable raised when exiting VR.
  79856. */
  79857. this.onExitingVRObservable = new BABYLON.Observable();
  79858. /**
  79859. * Observable raised when controller mesh is loaded.
  79860. */
  79861. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79862. this._useCustomVRButton = false;
  79863. this._teleportationRequested = false;
  79864. this._teleportationEnabledOnLeftController = false;
  79865. this._teleportationEnabledOnRightController = false;
  79866. this._interactionsEnabledOnLeftController = false;
  79867. this._interactionsEnabledOnRightController = false;
  79868. this._leftControllerReady = false;
  79869. this._rightControllerReady = false;
  79870. this._floorMeshesCollection = [];
  79871. this._teleportationAllowed = false;
  79872. this._rotationAllowed = true;
  79873. this._teleportationRequestInitiated = false;
  79874. this._teleportationBackRequestInitiated = false;
  79875. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  79876. this._rotationRightAsked = false;
  79877. this._rotationLeftAsked = false;
  79878. this._isDefaultTeleportationTarget = true;
  79879. this._teleportationFillColor = "#444444";
  79880. this._teleportationBorderColor = "#FFFFFF";
  79881. this._rotationAngle = 0;
  79882. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  79883. this._padSensibilityUp = 0.65;
  79884. this._padSensibilityDown = 0.35;
  79885. /**
  79886. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  79887. */
  79888. this.onNewMeshSelected = new BABYLON.Observable();
  79889. /**
  79890. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  79891. */
  79892. this.onNewMeshPicked = new BABYLON.Observable();
  79893. /**
  79894. * Observable raised before camera teleportation
  79895. */
  79896. this.onBeforeCameraTeleport = new BABYLON.Observable();
  79897. /**
  79898. * Observable raised after camera teleportation
  79899. */
  79900. this.onAfterCameraTeleport = new BABYLON.Observable();
  79901. /**
  79902. * Observable raised when current selected mesh gets unselected
  79903. */
  79904. this.onSelectedMeshUnselected = new BABYLON.Observable();
  79905. /**
  79906. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  79907. */
  79908. this.teleportationEnabled = true;
  79909. this._pointerDownOnMeshAsked = false;
  79910. this._isActionableMesh = false;
  79911. this._teleportationInitialized = false;
  79912. this._interactionsEnabled = false;
  79913. this._interactionsRequested = false;
  79914. this._displayGaze = true;
  79915. this._displayLaserPointer = true;
  79916. this._dpadPressed = true;
  79917. this._onResize = function () {
  79918. _this.moveButtonToBottomRight();
  79919. if (_this._fullscreenVRpresenting && _this._webVRready) {
  79920. _this.exitVR();
  79921. }
  79922. };
  79923. this._onFullscreenChange = function () {
  79924. if (document.fullscreen !== undefined) {
  79925. _this._fullscreenVRpresenting = document.fullscreen;
  79926. }
  79927. else if (document.mozFullScreen !== undefined) {
  79928. _this._fullscreenVRpresenting = document.mozFullScreen;
  79929. }
  79930. else if (document.webkitIsFullScreen !== undefined) {
  79931. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  79932. }
  79933. else if (document.msIsFullScreen !== undefined) {
  79934. _this._fullscreenVRpresenting = document.msIsFullScreen;
  79935. }
  79936. if (!_this._fullscreenVRpresenting && _this._canvas) {
  79937. _this.exitVR();
  79938. if (!_this._useCustomVRButton) {
  79939. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  79940. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  79941. }
  79942. }
  79943. };
  79944. this.beforeRender = function () {
  79945. _this._castRayAndSelectObject();
  79946. };
  79947. this._onNewGamepadConnected = function (gamepad) {
  79948. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  79949. if (gamepad.leftStick) {
  79950. gamepad.onleftstickchanged(function (stickValues) {
  79951. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  79952. // Listening to classic/xbox gamepad only if no VR controller is active
  79953. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  79954. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  79955. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  79956. _this._checkTeleportWithRay(stickValues);
  79957. _this._checkTeleportBackwards(stickValues);
  79958. }
  79959. }
  79960. });
  79961. }
  79962. if (gamepad.rightStick) {
  79963. gamepad.onrightstickchanged(function (stickValues) {
  79964. if (_this._teleportationInitialized) {
  79965. _this._checkRotate(stickValues);
  79966. }
  79967. });
  79968. }
  79969. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  79970. gamepad.onbuttondown(function (buttonPressed) {
  79971. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  79972. _this._selectionPointerDown();
  79973. }
  79974. });
  79975. gamepad.onbuttonup(function (buttonPressed) {
  79976. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  79977. _this._selectionPointerUp();
  79978. }
  79979. });
  79980. }
  79981. }
  79982. else {
  79983. var webVRController = gamepad;
  79984. _this._tryEnableInteractionOnController(webVRController);
  79985. }
  79986. };
  79987. // 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
  79988. this._tryEnableInteractionOnController = function (webVRController) {
  79989. if (webVRController.hand === "left") {
  79990. _this._leftControllerReady = true;
  79991. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  79992. _this._enableInteractionOnController(webVRController);
  79993. }
  79994. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  79995. _this._enableTeleportationOnController(webVRController);
  79996. }
  79997. }
  79998. if (webVRController.hand === "right") {
  79999. _this._rightControllerReady = true;
  80000. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  80001. _this._enableInteractionOnController(webVRController);
  80002. }
  80003. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  80004. _this._enableTeleportationOnController(webVRController);
  80005. }
  80006. }
  80007. };
  80008. this._onNewGamepadDisconnected = function (gamepad) {
  80009. if (gamepad instanceof BABYLON.WebVRController) {
  80010. if (gamepad.hand === "left") {
  80011. _this._interactionsEnabledOnLeftController = false;
  80012. _this._teleportationEnabledOnLeftController = false;
  80013. _this._leftControllerReady = false;
  80014. if (_this._leftLaserPointer) {
  80015. _this._leftLaserPointer.dispose();
  80016. }
  80017. }
  80018. if (gamepad.hand === "right") {
  80019. _this._interactionsEnabledOnRightController = false;
  80020. _this._teleportationEnabledOnRightController = false;
  80021. _this._rightControllerReady = false;
  80022. if (_this._rightLaserPointer) {
  80023. _this._rightLaserPointer.dispose();
  80024. }
  80025. }
  80026. }
  80027. };
  80028. this._workingVector = BABYLON.Vector3.Zero();
  80029. this._workingQuaternion = BABYLON.Quaternion.Identity();
  80030. this._workingMatrix = BABYLON.Matrix.Identity();
  80031. this._scene = scene;
  80032. this._canvas = scene.getEngine().getRenderingCanvas();
  80033. // Parse options
  80034. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  80035. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  80036. }
  80037. if (webVROptions.createDeviceOrientationCamera === undefined) {
  80038. webVROptions.createDeviceOrientationCamera = true;
  80039. }
  80040. if (webVROptions.defaultHeight === undefined) {
  80041. webVROptions.defaultHeight = 1.7;
  80042. }
  80043. if (webVROptions.useCustomVRButton) {
  80044. this._useCustomVRButton = true;
  80045. if (webVROptions.customVRButton) {
  80046. this._btnVR = webVROptions.customVRButton;
  80047. }
  80048. }
  80049. if (webVROptions.rayLength) {
  80050. this._rayLength = webVROptions.rayLength;
  80051. }
  80052. this._defaultHeight = webVROptions.defaultHeight;
  80053. // Set position
  80054. if (this._scene.activeCamera) {
  80055. this._position = this._scene.activeCamera.position.clone();
  80056. }
  80057. else {
  80058. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  80059. }
  80060. // Set non-vr camera
  80061. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  80062. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  80063. // Copy data from existing camera
  80064. if (this._scene.activeCamera) {
  80065. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  80066. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  80067. // Set rotation from previous camera
  80068. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  80069. var targetCamera = this._scene.activeCamera;
  80070. if (targetCamera.rotationQuaternion) {
  80071. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  80072. }
  80073. else {
  80074. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  80075. }
  80076. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  80077. }
  80078. }
  80079. this._scene.activeCamera = this._deviceOrientationCamera;
  80080. if (this._canvas) {
  80081. this._scene.activeCamera.attachControl(this._canvas);
  80082. }
  80083. }
  80084. else {
  80085. this._existingCamera = this._scene.activeCamera;
  80086. }
  80087. // Create VR cameras
  80088. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80089. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  80090. }
  80091. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  80092. this._webVRCamera.useStandingMatrix();
  80093. // Create default button
  80094. if (!this._useCustomVRButton) {
  80095. this._btnVR = document.createElement("BUTTON");
  80096. this._btnVR.className = "babylonVRicon";
  80097. this._btnVR.id = "babylonVRiconbtn";
  80098. this._btnVR.title = "Click to switch to VR";
  80099. 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) }";
  80100. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  80101. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  80102. // css += ".babylonVRicon.vrdisplaysupported { }";
  80103. // css += ".babylonVRicon.vrdisplayready { }";
  80104. // css += ".babylonVRicon.vrdisplayrequesting { }";
  80105. var style = document.createElement('style');
  80106. style.appendChild(document.createTextNode(css));
  80107. document.getElementsByTagName('head')[0].appendChild(style);
  80108. this.moveButtonToBottomRight();
  80109. }
  80110. // VR button click event
  80111. if (this._btnVR) {
  80112. this._btnVR.addEventListener("click", function () {
  80113. if (!_this.isInVRMode) {
  80114. _this.enterVR();
  80115. }
  80116. else {
  80117. _this.exitVR();
  80118. }
  80119. });
  80120. }
  80121. // Window events
  80122. window.addEventListener("resize", this._onResize);
  80123. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  80124. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  80125. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  80126. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  80127. // Display vr button when headset is connected
  80128. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80129. this.displayVRButton();
  80130. }
  80131. else {
  80132. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  80133. if (e.vrDisplay) {
  80134. _this.displayVRButton();
  80135. }
  80136. });
  80137. }
  80138. // Exiting VR mode using 'ESC' key on desktop
  80139. this._onKeyDown = function (event) {
  80140. if (event.keyCode === 27 && _this.isInVRMode) {
  80141. _this.exitVR();
  80142. }
  80143. };
  80144. document.addEventListener("keydown", this._onKeyDown);
  80145. // Exiting VR mode double tapping the touch screen
  80146. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  80147. if (_this.isInVRMode) {
  80148. _this.exitVR();
  80149. if (_this._fullscreenVRpresenting) {
  80150. _this._scene.getEngine().switchFullscreen(true);
  80151. }
  80152. }
  80153. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  80154. // Listen for WebVR display changes
  80155. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  80156. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  80157. this._onVRRequestPresentStart = function () {
  80158. _this._webVRrequesting = true;
  80159. _this.updateButtonVisibility();
  80160. };
  80161. this._onVRRequestPresentComplete = function (success) {
  80162. _this._webVRrequesting = false;
  80163. _this.updateButtonVisibility();
  80164. };
  80165. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  80166. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  80167. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  80168. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80169. scene.onDisposeObservable.add(function () {
  80170. _this.dispose();
  80171. });
  80172. // Gamepad connection events
  80173. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  80174. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  80175. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  80176. this.updateButtonVisibility();
  80177. //create easing functions
  80178. this._circleEase = new BABYLON.CircleEase();
  80179. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80180. }
  80181. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  80182. /** Return this.onEnteringVRObservable
  80183. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  80184. */
  80185. get: function () {
  80186. return this.onEnteringVRObservable;
  80187. },
  80188. enumerable: true,
  80189. configurable: true
  80190. });
  80191. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  80192. /** Return this.onExitingVRObservable
  80193. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  80194. */
  80195. get: function () {
  80196. return this.onExitingVRObservable;
  80197. },
  80198. enumerable: true,
  80199. configurable: true
  80200. });
  80201. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  80202. /** Return this.onControllerMeshLoadedObservable
  80203. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  80204. */
  80205. get: function () {
  80206. return this.onControllerMeshLoadedObservable;
  80207. },
  80208. enumerable: true,
  80209. configurable: true
  80210. });
  80211. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  80212. /**
  80213. * The mesh used to display where the user is going to teleport.
  80214. */
  80215. get: function () {
  80216. return this._teleportationTarget;
  80217. },
  80218. /**
  80219. * Sets the mesh to be used to display where the user is going to teleport.
  80220. */
  80221. set: function (value) {
  80222. if (value) {
  80223. value.name = "teleportationTarget";
  80224. this._isDefaultTeleportationTarget = false;
  80225. this._teleportationTarget = value;
  80226. }
  80227. },
  80228. enumerable: true,
  80229. configurable: true
  80230. });
  80231. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  80232. /**
  80233. * The mesh used to display where the user is selecting,
  80234. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  80235. * See http://doc.babylonjs.com/resources/baking_transformations
  80236. */
  80237. get: function () {
  80238. return this._gazeTracker;
  80239. },
  80240. set: function (value) {
  80241. if (value) {
  80242. this._gazeTracker = value;
  80243. this._gazeTracker.bakeCurrentTransformIntoVertices();
  80244. this._gazeTracker.isPickable = false;
  80245. this._gazeTracker.isVisible = false;
  80246. }
  80247. },
  80248. enumerable: true,
  80249. configurable: true
  80250. });
  80251. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  80252. /**
  80253. * If the ray of the gaze should be displayed.
  80254. */
  80255. get: function () {
  80256. return this._displayGaze;
  80257. },
  80258. /**
  80259. * Sets if the ray of the gaze should be displayed.
  80260. */
  80261. set: function (value) {
  80262. this._displayGaze = value;
  80263. if (!value) {
  80264. this._gazeTracker.isVisible = false;
  80265. }
  80266. },
  80267. enumerable: true,
  80268. configurable: true
  80269. });
  80270. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  80271. /**
  80272. * If the ray of the LaserPointer should be displayed.
  80273. */
  80274. get: function () {
  80275. return this._displayLaserPointer;
  80276. },
  80277. /**
  80278. * Sets if the ray of the LaserPointer should be displayed.
  80279. */
  80280. set: function (value) {
  80281. this._displayLaserPointer = value;
  80282. if (!value) {
  80283. if (this._rightLaserPointer) {
  80284. this._rightLaserPointer.isVisible = false;
  80285. }
  80286. if (this._leftLaserPointer) {
  80287. this._leftLaserPointer.isVisible = false;
  80288. }
  80289. }
  80290. else {
  80291. if (this._rightLaserPointer) {
  80292. this._rightLaserPointer.isVisible = true;
  80293. }
  80294. else if (this._leftLaserPointer) {
  80295. this._leftLaserPointer.isVisible = true;
  80296. }
  80297. }
  80298. },
  80299. enumerable: true,
  80300. configurable: true
  80301. });
  80302. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  80303. /**
  80304. * The deviceOrientationCamera used as the camera when not in VR.
  80305. */
  80306. get: function () {
  80307. return this._deviceOrientationCamera;
  80308. },
  80309. enumerable: true,
  80310. configurable: true
  80311. });
  80312. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  80313. /**
  80314. * Based on the current WebVR support, returns the current VR camera used.
  80315. */
  80316. get: function () {
  80317. if (this._webVRready) {
  80318. return this._webVRCamera;
  80319. }
  80320. else {
  80321. return this._scene.activeCamera;
  80322. }
  80323. },
  80324. enumerable: true,
  80325. configurable: true
  80326. });
  80327. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  80328. /**
  80329. * The webVRCamera which is used when in VR.
  80330. */
  80331. get: function () {
  80332. return this._webVRCamera;
  80333. },
  80334. enumerable: true,
  80335. configurable: true
  80336. });
  80337. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  80338. /**
  80339. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  80340. */
  80341. get: function () {
  80342. return this._vrDeviceOrientationCamera;
  80343. },
  80344. enumerable: true,
  80345. configurable: true
  80346. });
  80347. // Raised when one of the controller has loaded successfully its associated default mesh
  80348. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  80349. this._tryEnableInteractionOnController(webVRController);
  80350. try {
  80351. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  80352. }
  80353. catch (err) {
  80354. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  80355. }
  80356. };
  80357. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  80358. /**
  80359. * Gets a value indicating if we are currently in VR mode.
  80360. */
  80361. get: function () {
  80362. return this._webVRpresenting || this._fullscreenVRpresenting;
  80363. },
  80364. enumerable: true,
  80365. configurable: true
  80366. });
  80367. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  80368. var vrDisplay = this._scene.getEngine().getVRDevice();
  80369. if (vrDisplay) {
  80370. var wasPresenting = this._webVRpresenting;
  80371. // A VR display is connected
  80372. this._webVRpresenting = vrDisplay.isPresenting;
  80373. if (wasPresenting && !this._webVRpresenting)
  80374. this.exitVR();
  80375. }
  80376. else {
  80377. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  80378. }
  80379. this.updateButtonVisibility();
  80380. };
  80381. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  80382. this._webVRsupported = eventArgs.vrSupported;
  80383. this._webVRready = !!eventArgs.vrDisplay;
  80384. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  80385. this.updateButtonVisibility();
  80386. };
  80387. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  80388. if (this._canvas && !this._useCustomVRButton) {
  80389. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  80390. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  80391. }
  80392. };
  80393. VRExperienceHelper.prototype.displayVRButton = function () {
  80394. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  80395. document.body.appendChild(this._btnVR);
  80396. this._btnVRDisplayed = true;
  80397. }
  80398. };
  80399. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  80400. if (!this._btnVR || this._useCustomVRButton) {
  80401. return;
  80402. }
  80403. this._btnVR.className = "babylonVRicon";
  80404. if (this.isInVRMode) {
  80405. this._btnVR.className += " vrdisplaypresenting";
  80406. }
  80407. else {
  80408. if (this._webVRready)
  80409. this._btnVR.className += " vrdisplayready";
  80410. if (this._webVRsupported)
  80411. this._btnVR.className += " vrdisplaysupported";
  80412. if (this._webVRrequesting)
  80413. this._btnVR.className += " vrdisplayrequesting";
  80414. }
  80415. };
  80416. /**
  80417. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  80418. * Otherwise, will use the fullscreen API.
  80419. */
  80420. VRExperienceHelper.prototype.enterVR = function () {
  80421. if (this.onEnteringVRObservable) {
  80422. try {
  80423. this.onEnteringVRObservable.notifyObservers(this);
  80424. }
  80425. catch (err) {
  80426. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  80427. }
  80428. }
  80429. if (this._scene.activeCamera) {
  80430. this._position = this._scene.activeCamera.position.clone();
  80431. // make sure that we return to the last active camera
  80432. this._existingCamera = this._scene.activeCamera;
  80433. }
  80434. if (this._webVRrequesting)
  80435. return;
  80436. // If WebVR is supported and a headset is connected
  80437. if (this._webVRready) {
  80438. if (!this._webVRpresenting) {
  80439. this._webVRCamera.position = this._position;
  80440. this._scene.activeCamera = this._webVRCamera;
  80441. }
  80442. }
  80443. else if (this._vrDeviceOrientationCamera) {
  80444. this._vrDeviceOrientationCamera.position = this._position;
  80445. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  80446. this._scene.getEngine().switchFullscreen(true);
  80447. this.updateButtonVisibility();
  80448. }
  80449. if (this._scene.activeCamera && this._canvas) {
  80450. this._scene.activeCamera.attachControl(this._canvas);
  80451. }
  80452. if (this._interactionsEnabled) {
  80453. this._scene.registerBeforeRender(this.beforeRender);
  80454. }
  80455. };
  80456. /**
  80457. * Attempt to exit VR, or fullscreen.
  80458. */
  80459. VRExperienceHelper.prototype.exitVR = function () {
  80460. if (this.onExitingVRObservable) {
  80461. try {
  80462. this.onExitingVRObservable.notifyObservers(this);
  80463. }
  80464. catch (err) {
  80465. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  80466. }
  80467. }
  80468. if (this._webVRpresenting) {
  80469. this._scene.getEngine().disableVR();
  80470. }
  80471. if (this._scene.activeCamera) {
  80472. this._position = this._scene.activeCamera.position.clone();
  80473. }
  80474. if (this._deviceOrientationCamera) {
  80475. this._deviceOrientationCamera.position = this._position;
  80476. this._scene.activeCamera = this._deviceOrientationCamera;
  80477. if (this._canvas) {
  80478. this._scene.activeCamera.attachControl(this._canvas);
  80479. }
  80480. }
  80481. else if (this._existingCamera) {
  80482. this._existingCamera.position = this._position;
  80483. this._scene.activeCamera = this._existingCamera;
  80484. }
  80485. this.updateButtonVisibility();
  80486. if (this._interactionsEnabled) {
  80487. this._scene.unregisterBeforeRender(this.beforeRender);
  80488. }
  80489. };
  80490. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  80491. /**
  80492. * The position of the vr experience helper.
  80493. */
  80494. get: function () {
  80495. return this._position;
  80496. },
  80497. /**
  80498. * Sets the position of the vr experience helper.
  80499. */
  80500. set: function (value) {
  80501. this._position = value;
  80502. if (this._scene.activeCamera) {
  80503. this._scene.activeCamera.position = value;
  80504. }
  80505. },
  80506. enumerable: true,
  80507. configurable: true
  80508. });
  80509. /**
  80510. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  80511. */
  80512. VRExperienceHelper.prototype.enableInteractions = function () {
  80513. var _this = this;
  80514. if (!this._interactionsEnabled) {
  80515. this._interactionsRequested = true;
  80516. if (this._leftControllerReady && this._webVRCamera.leftController) {
  80517. this._enableInteractionOnController(this._webVRCamera.leftController);
  80518. }
  80519. if (this._rightControllerReady && this._webVRCamera.rightController) {
  80520. this._enableInteractionOnController(this._webVRCamera.rightController);
  80521. }
  80522. if (!this._gazeTracker) {
  80523. this._createGazeTracker();
  80524. }
  80525. this.raySelectionPredicate = function (mesh) {
  80526. return mesh.isVisible;
  80527. };
  80528. this.meshSelectionPredicate = function (mesh) {
  80529. return true;
  80530. };
  80531. this._raySelectionPredicate = function (mesh) {
  80532. if (_this._isTeleportationFloor(mesh) || (mesh != _this._gazeTracker
  80533. && mesh.name.indexOf("teleportationTarget") === -1
  80534. && mesh.name.indexOf("torusTeleportation") === -1
  80535. && mesh.name.indexOf("laserPointer") === -1)) {
  80536. return _this.raySelectionPredicate(mesh);
  80537. }
  80538. return false;
  80539. };
  80540. this._interactionsEnabled = true;
  80541. }
  80542. };
  80543. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  80544. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  80545. if (this._floorMeshesCollection[i].id === mesh.id) {
  80546. return true;
  80547. }
  80548. }
  80549. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  80550. return true;
  80551. }
  80552. return false;
  80553. };
  80554. /**
  80555. * Adds a floor mesh to be used for teleportation.
  80556. * @param floorMesh the mesh to be used for teleportation.
  80557. */
  80558. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  80559. if (!this._floorMeshesCollection) {
  80560. return;
  80561. }
  80562. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  80563. return;
  80564. }
  80565. this._floorMeshesCollection.push(floorMesh);
  80566. };
  80567. /**
  80568. * Removes a floor mesh from being used for teleportation.
  80569. * @param floorMesh the mesh to be removed.
  80570. */
  80571. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  80572. if (!this._floorMeshesCollection) {
  80573. return;
  80574. }
  80575. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  80576. if (meshIndex !== -1) {
  80577. this._floorMeshesCollection.splice(meshIndex, 1);
  80578. }
  80579. };
  80580. /**
  80581. * Enables interactions and teleportation using the VR controllers and gaze.
  80582. * @param vrTeleportationOptions options to modify teleportation behavior.
  80583. */
  80584. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  80585. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  80586. if (!this._teleportationInitialized) {
  80587. this._teleportationRequested = true;
  80588. this.enableInteractions();
  80589. if (vrTeleportationOptions.floorMeshName) {
  80590. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  80591. }
  80592. if (vrTeleportationOptions.floorMeshes) {
  80593. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  80594. }
  80595. if (this._leftControllerReady && this._webVRCamera.leftController) {
  80596. this._enableTeleportationOnController(this._webVRCamera.leftController);
  80597. }
  80598. if (this._rightControllerReady && this._webVRCamera.rightController) {
  80599. this._enableTeleportationOnController(this._webVRCamera.rightController);
  80600. }
  80601. // Creates an image processing post process for the vignette not relying
  80602. // on the main scene configuration for image processing to reduce setup and spaces
  80603. // (gamma/linear) conflicts.
  80604. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  80605. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  80606. imageProcessingConfiguration.vignetteEnabled = true;
  80607. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  80608. this._webVRCamera.detachPostProcess(this._postProcessMove);
  80609. this._teleportationInitialized = true;
  80610. if (this._isDefaultTeleportationTarget) {
  80611. this._createTeleportationCircles();
  80612. }
  80613. }
  80614. };
  80615. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  80616. var _this = this;
  80617. var controllerMesh = webVRController.mesh;
  80618. if (controllerMesh) {
  80619. var makeNotPick = function (root) {
  80620. root.name += " laserPointer";
  80621. root.getChildMeshes().forEach(function (c) {
  80622. makeNotPick(c);
  80623. });
  80624. };
  80625. makeNotPick(controllerMesh);
  80626. var childMeshes = controllerMesh.getChildMeshes();
  80627. for (var i = 0; i < childMeshes.length; i++) {
  80628. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  80629. controllerMesh = childMeshes[i];
  80630. break;
  80631. }
  80632. }
  80633. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  80634. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  80635. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80636. laserPointerMaterial.alpha = 0.6;
  80637. laserPointer.material = laserPointerMaterial;
  80638. laserPointer.rotation.x = Math.PI / 2;
  80639. laserPointer.parent = controllerMesh;
  80640. laserPointer.position.z = -0.5;
  80641. laserPointer.isVisible = false;
  80642. if (webVRController.hand === "left") {
  80643. this._leftLaserPointer = laserPointer;
  80644. this._interactionsEnabledOnLeftController = true;
  80645. if (!this._rightLaserPointer) {
  80646. this._leftLaserPointer.isVisible = true;
  80647. }
  80648. }
  80649. else {
  80650. this._rightLaserPointer = laserPointer;
  80651. this._interactionsEnabledOnRightController = true;
  80652. if (!this._leftLaserPointer) {
  80653. this._rightLaserPointer.isVisible = true;
  80654. }
  80655. }
  80656. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  80657. // Enabling / disabling laserPointer
  80658. if (_this._displayLaserPointer && stateObject.value === 1) {
  80659. laserPointer.isVisible = !laserPointer.isVisible;
  80660. // Laser pointer can only be active on left or right, not both at the same time
  80661. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  80662. _this._rightLaserPointer.isVisible = false;
  80663. }
  80664. else if (_this._leftLaserPointer) {
  80665. _this._leftLaserPointer.isVisible = false;
  80666. }
  80667. }
  80668. });
  80669. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  80670. if (!_this._pointerDownOnMeshAsked) {
  80671. if (stateObject.value > _this._padSensibilityUp) {
  80672. _this._selectionPointerDown();
  80673. }
  80674. }
  80675. else if (stateObject.value < _this._padSensibilityDown) {
  80676. _this._selectionPointerUp();
  80677. }
  80678. });
  80679. }
  80680. };
  80681. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  80682. if (webVRController === void 0) { webVRController = null; }
  80683. if (!this._teleportationRequestInitiated) {
  80684. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  80685. if (webVRController) {
  80686. // If laser pointer wasn't enabled yet
  80687. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  80688. this._leftLaserPointer.isVisible = true;
  80689. if (this._rightLaserPointer) {
  80690. this._rightLaserPointer.isVisible = false;
  80691. }
  80692. }
  80693. else if (this._displayLaserPointer && this._rightLaserPointer) {
  80694. this._rightLaserPointer.isVisible = true;
  80695. if (this._leftLaserPointer) {
  80696. this._leftLaserPointer.isVisible = false;
  80697. }
  80698. }
  80699. }
  80700. this._teleportationRequestInitiated = true;
  80701. }
  80702. }
  80703. else {
  80704. // Listening to the proper controller values changes to confirm teleportation
  80705. if (webVRController == null
  80706. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  80707. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  80708. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  80709. if (this._teleportationAllowed) {
  80710. this._teleportationAllowed = false;
  80711. this._teleportCamera();
  80712. }
  80713. this._teleportationRequestInitiated = false;
  80714. }
  80715. }
  80716. }
  80717. };
  80718. VRExperienceHelper.prototype._selectionPointerDown = function () {
  80719. this._pointerDownOnMeshAsked = true;
  80720. if (this._currentMeshSelected && this._currentHit) {
  80721. this._scene.simulatePointerDown(this._currentHit);
  80722. }
  80723. };
  80724. VRExperienceHelper.prototype._selectionPointerUp = function () {
  80725. if (this._currentMeshSelected && this._currentHit) {
  80726. this._scene.simulatePointerUp(this._currentHit);
  80727. }
  80728. this._pointerDownOnMeshAsked = false;
  80729. };
  80730. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  80731. // Only rotate when user is not currently selecting a teleportation location
  80732. if (this._teleportationRequestInitiated) {
  80733. return;
  80734. }
  80735. if (!this._rotationLeftAsked) {
  80736. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  80737. this._rotationLeftAsked = true;
  80738. if (this._rotationAllowed) {
  80739. this._rotateCamera(false);
  80740. }
  80741. }
  80742. }
  80743. else {
  80744. if (stateObject.x > -this._padSensibilityDown) {
  80745. this._rotationLeftAsked = false;
  80746. }
  80747. }
  80748. if (!this._rotationRightAsked) {
  80749. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  80750. this._rotationRightAsked = true;
  80751. if (this._rotationAllowed) {
  80752. this._rotateCamera(true);
  80753. }
  80754. }
  80755. }
  80756. else {
  80757. if (stateObject.x < this._padSensibilityDown) {
  80758. this._rotationRightAsked = false;
  80759. }
  80760. }
  80761. };
  80762. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  80763. // Only teleport backwards when user is not currently selecting a teleportation location
  80764. if (this._teleportationRequestInitiated) {
  80765. return;
  80766. }
  80767. // Teleport backwards
  80768. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  80769. if (!this._teleportationBackRequestInitiated) {
  80770. if (!this.currentVRCamera) {
  80771. return;
  80772. }
  80773. // Get rotation and position of the current camera
  80774. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  80775. var position = this.currentVRCamera.position;
  80776. // If the camera has device position, use that instead
  80777. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  80778. rotation = this.currentVRCamera.deviceRotationQuaternion;
  80779. position = this.currentVRCamera.devicePosition;
  80780. }
  80781. // Get matrix with only the y rotation of the device rotation
  80782. rotation.toEulerAnglesToRef(this._workingVector);
  80783. this._workingVector.z = 0;
  80784. this._workingVector.x = 0;
  80785. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  80786. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  80787. // Rotate backwards ray by device rotation to cast at the ground behind the user
  80788. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  80789. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  80790. var ray = new BABYLON.Ray(position, this._workingVector);
  80791. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  80792. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  80793. this._teleportCamera(hit.pickedPoint);
  80794. }
  80795. this._teleportationBackRequestInitiated = true;
  80796. }
  80797. }
  80798. else {
  80799. this._teleportationBackRequestInitiated = false;
  80800. }
  80801. };
  80802. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  80803. var _this = this;
  80804. var controllerMesh = webVRController.mesh;
  80805. if (controllerMesh) {
  80806. if (webVRController.hand === "left") {
  80807. if (!this._interactionsEnabledOnLeftController) {
  80808. this._enableInteractionOnController(webVRController);
  80809. }
  80810. this._teleportationEnabledOnLeftController = true;
  80811. }
  80812. else {
  80813. if (!this._interactionsEnabledOnRightController) {
  80814. this._enableInteractionOnController(webVRController);
  80815. }
  80816. this._teleportationEnabledOnRightController = true;
  80817. }
  80818. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80819. this._dpadPressed = false;
  80820. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  80821. _this._dpadPressed = stateObject.pressed;
  80822. if (!_this._dpadPressed) {
  80823. _this._rotationLeftAsked = false;
  80824. _this._rotationRightAsked = false;
  80825. _this._teleportationBackRequestInitiated = false;
  80826. }
  80827. });
  80828. }
  80829. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  80830. if (_this.teleportationEnabled) {
  80831. _this._checkTeleportBackwards(stateObject);
  80832. _this._checkTeleportWithRay(stateObject, webVRController);
  80833. }
  80834. _this._checkRotate(stateObject);
  80835. });
  80836. }
  80837. };
  80838. // Gaze support used to point to teleport or to interact with an object
  80839. VRExperienceHelper.prototype._createGazeTracker = function () {
  80840. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  80841. this._gazeTracker.bakeCurrentTransformIntoVertices();
  80842. this._gazeTracker.isPickable = false;
  80843. this._gazeTracker.isVisible = false;
  80844. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  80845. targetMat.specularColor = BABYLON.Color3.Black();
  80846. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80847. targetMat.backFaceCulling = false;
  80848. this._gazeTracker.material = targetMat;
  80849. };
  80850. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  80851. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  80852. this._teleportationTarget.isPickable = false;
  80853. var length = 512;
  80854. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  80855. dynamicTexture.hasAlpha = true;
  80856. var context = dynamicTexture.getContext();
  80857. var centerX = length / 2;
  80858. var centerY = length / 2;
  80859. var radius = 200;
  80860. context.beginPath();
  80861. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  80862. context.fillStyle = this._teleportationFillColor;
  80863. context.fill();
  80864. context.lineWidth = 10;
  80865. context.strokeStyle = this._teleportationBorderColor;
  80866. context.stroke();
  80867. context.closePath();
  80868. dynamicTexture.update();
  80869. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  80870. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  80871. this._teleportationTarget.material = teleportationCircleMaterial;
  80872. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  80873. torus.isPickable = false;
  80874. torus.parent = this._teleportationTarget;
  80875. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  80876. var keys = [];
  80877. keys.push({
  80878. frame: 0,
  80879. value: 0
  80880. });
  80881. keys.push({
  80882. frame: 30,
  80883. value: 0.4
  80884. });
  80885. keys.push({
  80886. frame: 60,
  80887. value: 0
  80888. });
  80889. animationInnerCircle.setKeys(keys);
  80890. var easingFunction = new BABYLON.SineEase();
  80891. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80892. animationInnerCircle.setEasingFunction(easingFunction);
  80893. torus.animations = [];
  80894. torus.animations.push(animationInnerCircle);
  80895. this._scene.beginAnimation(torus, 0, 60, true);
  80896. this._hideTeleportationTarget();
  80897. };
  80898. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  80899. if (this._teleportationInitialized) {
  80900. this._teleportationTarget.isVisible = true;
  80901. if (this._isDefaultTeleportationTarget) {
  80902. this._teleportationTarget.getChildren()[0].isVisible = true;
  80903. }
  80904. }
  80905. };
  80906. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  80907. if (this._teleportationInitialized) {
  80908. this._teleportationTarget.isVisible = false;
  80909. if (this._isDefaultTeleportationTarget) {
  80910. this._teleportationTarget.getChildren()[0].isVisible = false;
  80911. }
  80912. }
  80913. };
  80914. VRExperienceHelper.prototype._rotateCamera = function (right) {
  80915. var _this = this;
  80916. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  80917. return;
  80918. }
  80919. if (right) {
  80920. this._rotationAngle++;
  80921. }
  80922. else {
  80923. this._rotationAngle--;
  80924. }
  80925. this.currentVRCamera.animations = [];
  80926. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  80927. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80928. var animationRotationKeys = [];
  80929. animationRotationKeys.push({
  80930. frame: 0,
  80931. value: this.currentVRCamera.rotationQuaternion
  80932. });
  80933. animationRotationKeys.push({
  80934. frame: 6,
  80935. value: target
  80936. });
  80937. animationRotation.setKeys(animationRotationKeys);
  80938. animationRotation.setEasingFunction(this._circleEase);
  80939. this.currentVRCamera.animations.push(animationRotation);
  80940. this._postProcessMove.animations = [];
  80941. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80942. var vignetteWeightKeys = [];
  80943. vignetteWeightKeys.push({
  80944. frame: 0,
  80945. value: 0
  80946. });
  80947. vignetteWeightKeys.push({
  80948. frame: 3,
  80949. value: 4
  80950. });
  80951. vignetteWeightKeys.push({
  80952. frame: 6,
  80953. value: 0
  80954. });
  80955. animationPP.setKeys(vignetteWeightKeys);
  80956. animationPP.setEasingFunction(this._circleEase);
  80957. this._postProcessMove.animations.push(animationPP);
  80958. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80959. var vignetteStretchKeys = [];
  80960. vignetteStretchKeys.push({
  80961. frame: 0,
  80962. value: 0
  80963. });
  80964. vignetteStretchKeys.push({
  80965. frame: 3,
  80966. value: 10
  80967. });
  80968. vignetteStretchKeys.push({
  80969. frame: 6,
  80970. value: 0
  80971. });
  80972. animationPP2.setKeys(vignetteStretchKeys);
  80973. animationPP2.setEasingFunction(this._circleEase);
  80974. this._postProcessMove.animations.push(animationPP2);
  80975. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  80976. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  80977. this._postProcessMove.samples = 4;
  80978. this._webVRCamera.attachPostProcess(this._postProcessMove);
  80979. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  80980. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  80981. });
  80982. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  80983. };
  80984. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  80985. if (hit.pickedPoint) {
  80986. this._teleportationAllowed = true;
  80987. if (this._teleportationRequestInitiated) {
  80988. this._displayTeleportationTarget();
  80989. }
  80990. else {
  80991. this._hideTeleportationTarget();
  80992. }
  80993. this._haloCenter.copyFrom(hit.pickedPoint);
  80994. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  80995. var pickNormal = hit.getNormal(true, false);
  80996. if (pickNormal) {
  80997. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  80998. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  80999. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  81000. }
  81001. this._teleportationTarget.position.y += 0.1;
  81002. }
  81003. };
  81004. VRExperienceHelper.prototype._teleportCamera = function (location) {
  81005. var _this = this;
  81006. if (location === void 0) { location = null; }
  81007. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81008. return;
  81009. }
  81010. if (!location) {
  81011. location = this._haloCenter;
  81012. }
  81013. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  81014. // offset of the headset from the anchor.
  81015. if (this.webVRCamera.leftCamera) {
  81016. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  81017. this._workingVector.subtractInPlace(this.webVRCamera.position);
  81018. location.subtractToRef(this._workingVector, this._workingVector);
  81019. }
  81020. else {
  81021. this._workingVector.copyFrom(location);
  81022. }
  81023. // Add height to account for user's height offset
  81024. if (this.isInVRMode) {
  81025. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  81026. }
  81027. else {
  81028. this._workingVector.y += this._defaultHeight;
  81029. }
  81030. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  81031. // Create animation from the camera's position to the new location
  81032. this.currentVRCamera.animations = [];
  81033. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81034. var animationCameraTeleportationKeys = [{
  81035. frame: 0,
  81036. value: this.currentVRCamera.position
  81037. },
  81038. {
  81039. frame: 11,
  81040. value: this._workingVector
  81041. }
  81042. ];
  81043. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  81044. animationCameraTeleportation.setEasingFunction(this._circleEase);
  81045. this.currentVRCamera.animations.push(animationCameraTeleportation);
  81046. this._postProcessMove.animations = [];
  81047. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81048. var vignetteWeightKeys = [];
  81049. vignetteWeightKeys.push({
  81050. frame: 0,
  81051. value: 0
  81052. });
  81053. vignetteWeightKeys.push({
  81054. frame: 5,
  81055. value: 8
  81056. });
  81057. vignetteWeightKeys.push({
  81058. frame: 11,
  81059. value: 0
  81060. });
  81061. animationPP.setKeys(vignetteWeightKeys);
  81062. this._postProcessMove.animations.push(animationPP);
  81063. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81064. var vignetteStretchKeys = [];
  81065. vignetteStretchKeys.push({
  81066. frame: 0,
  81067. value: 0
  81068. });
  81069. vignetteStretchKeys.push({
  81070. frame: 5,
  81071. value: 10
  81072. });
  81073. vignetteStretchKeys.push({
  81074. frame: 11,
  81075. value: 0
  81076. });
  81077. animationPP2.setKeys(vignetteStretchKeys);
  81078. this._postProcessMove.animations.push(animationPP2);
  81079. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81080. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81081. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81082. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  81083. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81084. });
  81085. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  81086. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  81087. });
  81088. };
  81089. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  81090. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81091. return;
  81092. }
  81093. var ray;
  81094. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  81095. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  81096. }
  81097. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  81098. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  81099. }
  81100. else {
  81101. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  81102. }
  81103. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  81104. // Moving the gazeTracker on the mesh face targetted
  81105. if (hit && hit.pickedPoint) {
  81106. if (this._displayGaze) {
  81107. var multiplier = 1;
  81108. this._gazeTracker.isVisible = true;
  81109. if (this._isActionableMesh) {
  81110. multiplier = 3;
  81111. }
  81112. this._gazeTracker.scaling.x = hit.distance * multiplier;
  81113. this._gazeTracker.scaling.y = hit.distance * multiplier;
  81114. this._gazeTracker.scaling.z = hit.distance * multiplier;
  81115. var pickNormal = hit.getNormal();
  81116. // To avoid z-fighting
  81117. var deltaFighting = 0.002;
  81118. if (pickNormal) {
  81119. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81120. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81121. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  81122. }
  81123. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  81124. if (this._gazeTracker.position.x < 0) {
  81125. this._gazeTracker.position.x += deltaFighting;
  81126. }
  81127. else {
  81128. this._gazeTracker.position.x -= deltaFighting;
  81129. }
  81130. if (this._gazeTracker.position.y < 0) {
  81131. this._gazeTracker.position.y += deltaFighting;
  81132. }
  81133. else {
  81134. this._gazeTracker.position.y -= deltaFighting;
  81135. }
  81136. if (this._gazeTracker.position.z < 0) {
  81137. this._gazeTracker.position.z += deltaFighting;
  81138. }
  81139. else {
  81140. this._gazeTracker.position.z -= deltaFighting;
  81141. }
  81142. }
  81143. // Changing the size of the laser pointer based on the distance from the targetted point
  81144. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  81145. this._rightLaserPointer.scaling.y = hit.distance;
  81146. this._rightLaserPointer.position.z = -hit.distance / 2;
  81147. }
  81148. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  81149. this._leftLaserPointer.scaling.y = hit.distance;
  81150. this._leftLaserPointer.position.z = -hit.distance / 2;
  81151. }
  81152. }
  81153. else {
  81154. this._gazeTracker.isVisible = false;
  81155. }
  81156. if (hit && hit.pickedMesh) {
  81157. this._currentHit = hit;
  81158. if (this._pointerDownOnMeshAsked) {
  81159. this._scene.simulatePointerMove(this._currentHit);
  81160. }
  81161. // The object selected is the floor, we're in a teleportation scenario
  81162. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  81163. // Moving the teleportation area to this targetted point
  81164. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  81165. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  81166. this._notifySelectedMeshUnselected();
  81167. }
  81168. this._currentMeshSelected = null;
  81169. this._moveTeleportationSelectorTo(hit);
  81170. return;
  81171. }
  81172. // If not, we're in a selection scenario
  81173. this._hideTeleportationTarget();
  81174. this._teleportationAllowed = false;
  81175. if (hit.pickedMesh !== this._currentMeshSelected) {
  81176. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  81177. this.onNewMeshPicked.notifyObservers(hit);
  81178. this._currentMeshSelected = hit.pickedMesh;
  81179. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  81180. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  81181. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  81182. this._isActionableMesh = true;
  81183. }
  81184. else {
  81185. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81186. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81187. this._isActionableMesh = false;
  81188. }
  81189. try {
  81190. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  81191. }
  81192. catch (err) {
  81193. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  81194. }
  81195. }
  81196. else {
  81197. this._notifySelectedMeshUnselected();
  81198. this._currentMeshSelected = null;
  81199. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81200. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81201. }
  81202. }
  81203. }
  81204. else {
  81205. this._currentHit = null;
  81206. this._notifySelectedMeshUnselected();
  81207. this._currentMeshSelected = null;
  81208. this._teleportationAllowed = false;
  81209. this._hideTeleportationTarget();
  81210. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81211. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81212. }
  81213. };
  81214. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  81215. if (this._currentMeshSelected) {
  81216. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  81217. }
  81218. };
  81219. /**
  81220. * Sets the color of the laser ray from the vr controllers.
  81221. * @param color new color for the ray.
  81222. */
  81223. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  81224. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  81225. this._leftLaserPointer.material.emissiveColor = color;
  81226. }
  81227. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  81228. this._rightLaserPointer.material.emissiveColor = color;
  81229. }
  81230. };
  81231. /**
  81232. * Sets the color of the ray from the vr headsets gaze.
  81233. * @param color new color for the ray.
  81234. */
  81235. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  81236. if (this._gazeTracker.material) {
  81237. this._gazeTracker.material.emissiveColor = color;
  81238. }
  81239. };
  81240. /**
  81241. * Exits VR and disposes of the vr experience helper
  81242. */
  81243. VRExperienceHelper.prototype.dispose = function () {
  81244. if (this.isInVRMode) {
  81245. this.exitVR();
  81246. }
  81247. if (this._postProcessMove) {
  81248. this._postProcessMove.dispose();
  81249. }
  81250. if (this._webVRCamera) {
  81251. this._webVRCamera.dispose();
  81252. }
  81253. if (this._vrDeviceOrientationCamera) {
  81254. this._vrDeviceOrientationCamera.dispose();
  81255. }
  81256. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  81257. document.body.removeChild(this._btnVR);
  81258. }
  81259. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  81260. this._deviceOrientationCamera.dispose();
  81261. }
  81262. if (this._gazeTracker) {
  81263. this._gazeTracker.dispose();
  81264. }
  81265. if (this._teleportationTarget) {
  81266. this._teleportationTarget.dispose();
  81267. }
  81268. this._floorMeshesCollection = [];
  81269. document.removeEventListener("keydown", this._onKeyDown);
  81270. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81271. window.removeEventListener("resize", this._onResize);
  81272. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  81273. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  81274. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  81275. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  81276. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  81277. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  81278. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  81279. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81280. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  81281. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  81282. this._scene.unregisterBeforeRender(this.beforeRender);
  81283. };
  81284. /**
  81285. * Gets the name of the VRExperienceHelper class
  81286. * @returns "VRExperienceHelper"
  81287. */
  81288. VRExperienceHelper.prototype.getClassName = function () {
  81289. return "VRExperienceHelper";
  81290. };
  81291. return VRExperienceHelper;
  81292. }());
  81293. BABYLON.VRExperienceHelper = VRExperienceHelper;
  81294. })(BABYLON || (BABYLON = {}));
  81295. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  81296. // Mainly based on these 2 articles :
  81297. // 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
  81298. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  81299. var BABYLON;
  81300. (function (BABYLON) {
  81301. var JoystickAxis;
  81302. (function (JoystickAxis) {
  81303. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  81304. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  81305. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  81306. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  81307. var VirtualJoystick = /** @class */ (function () {
  81308. function VirtualJoystick(leftJoystick) {
  81309. var _this = this;
  81310. if (leftJoystick) {
  81311. this._leftJoystick = true;
  81312. }
  81313. else {
  81314. this._leftJoystick = false;
  81315. }
  81316. VirtualJoystick._globalJoystickIndex++;
  81317. // By default left & right arrow keys are moving the X
  81318. // and up & down keys are moving the Y
  81319. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81320. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81321. this.reverseLeftRight = false;
  81322. this.reverseUpDown = false;
  81323. // collections of pointers
  81324. this._touches = new BABYLON.StringDictionary();
  81325. this.deltaPosition = BABYLON.Vector3.Zero();
  81326. this._joystickSensibility = 25;
  81327. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81328. this._onResize = function (evt) {
  81329. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81330. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81331. if (VirtualJoystick.vjCanvas) {
  81332. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  81333. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  81334. }
  81335. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  81336. };
  81337. // injecting a canvas element on top of the canvas 3D game
  81338. if (!VirtualJoystick.vjCanvas) {
  81339. window.addEventListener("resize", this._onResize, false);
  81340. VirtualJoystick.vjCanvas = document.createElement("canvas");
  81341. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81342. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81343. VirtualJoystick.vjCanvas.width = window.innerWidth;
  81344. VirtualJoystick.vjCanvas.height = window.innerHeight;
  81345. VirtualJoystick.vjCanvas.style.width = "100%";
  81346. VirtualJoystick.vjCanvas.style.height = "100%";
  81347. VirtualJoystick.vjCanvas.style.position = "absolute";
  81348. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  81349. VirtualJoystick.vjCanvas.style.top = "0px";
  81350. VirtualJoystick.vjCanvas.style.left = "0px";
  81351. VirtualJoystick.vjCanvas.style.zIndex = "5";
  81352. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  81353. // Support for jQuery PEP polyfill
  81354. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  81355. var context = VirtualJoystick.vjCanvas.getContext('2d');
  81356. if (!context) {
  81357. throw new Error("Unable to create canvas for virtual joystick");
  81358. }
  81359. VirtualJoystick.vjCanvasContext = context;
  81360. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  81361. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81362. document.body.appendChild(VirtualJoystick.vjCanvas);
  81363. }
  81364. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  81365. this.pressed = false;
  81366. // default joystick color
  81367. this._joystickColor = "cyan";
  81368. this._joystickPointerID = -1;
  81369. // current joystick position
  81370. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  81371. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  81372. // origin joystick position
  81373. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  81374. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  81375. this._onPointerDownHandlerRef = function (evt) {
  81376. _this._onPointerDown(evt);
  81377. };
  81378. this._onPointerMoveHandlerRef = function (evt) {
  81379. _this._onPointerMove(evt);
  81380. };
  81381. this._onPointerUpHandlerRef = function (evt) {
  81382. _this._onPointerUp(evt);
  81383. };
  81384. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  81385. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  81386. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  81387. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  81388. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  81389. evt.preventDefault(); // Disables system menu
  81390. }, false);
  81391. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81392. }
  81393. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  81394. this._joystickSensibility = newJoystickSensibility;
  81395. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81396. };
  81397. VirtualJoystick.prototype._onPointerDown = function (e) {
  81398. var positionOnScreenCondition;
  81399. e.preventDefault();
  81400. if (this._leftJoystick === true) {
  81401. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  81402. }
  81403. else {
  81404. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  81405. }
  81406. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  81407. // First contact will be dedicated to the virtual joystick
  81408. this._joystickPointerID = e.pointerId;
  81409. this._joystickPointerStartPos.x = e.clientX;
  81410. this._joystickPointerStartPos.y = e.clientY;
  81411. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  81412. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  81413. this._deltaJoystickVector.x = 0;
  81414. this._deltaJoystickVector.y = 0;
  81415. this.pressed = true;
  81416. this._touches.add(e.pointerId.toString(), e);
  81417. }
  81418. else {
  81419. // You can only trigger the action buttons with a joystick declared
  81420. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  81421. this._action();
  81422. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  81423. }
  81424. }
  81425. };
  81426. VirtualJoystick.prototype._onPointerMove = function (e) {
  81427. // If the current pointer is the one associated to the joystick (first touch contact)
  81428. if (this._joystickPointerID == e.pointerId) {
  81429. this._joystickPointerPos.x = e.clientX;
  81430. this._joystickPointerPos.y = e.clientY;
  81431. this._deltaJoystickVector = this._joystickPointerPos.clone();
  81432. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  81433. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  81434. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  81435. switch (this._axisTargetedByLeftAndRight) {
  81436. case JoystickAxis.X:
  81437. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  81438. break;
  81439. case JoystickAxis.Y:
  81440. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  81441. break;
  81442. case JoystickAxis.Z:
  81443. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  81444. break;
  81445. }
  81446. var directionUpDown = this.reverseUpDown ? 1 : -1;
  81447. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  81448. switch (this._axisTargetedByUpAndDown) {
  81449. case JoystickAxis.X:
  81450. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  81451. break;
  81452. case JoystickAxis.Y:
  81453. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  81454. break;
  81455. case JoystickAxis.Z:
  81456. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  81457. break;
  81458. }
  81459. }
  81460. else {
  81461. var data = this._touches.get(e.pointerId.toString());
  81462. if (data) {
  81463. data.x = e.clientX;
  81464. data.y = e.clientY;
  81465. }
  81466. }
  81467. };
  81468. VirtualJoystick.prototype._onPointerUp = function (e) {
  81469. if (this._joystickPointerID == e.pointerId) {
  81470. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  81471. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  81472. this._joystickPointerID = -1;
  81473. this.pressed = false;
  81474. }
  81475. else {
  81476. var touch = this._touches.get(e.pointerId.toString());
  81477. if (touch) {
  81478. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  81479. }
  81480. }
  81481. this._deltaJoystickVector.x = 0;
  81482. this._deltaJoystickVector.y = 0;
  81483. this._touches.remove(e.pointerId.toString());
  81484. };
  81485. /**
  81486. * Change the color of the virtual joystick
  81487. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  81488. */
  81489. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  81490. this._joystickColor = newColor;
  81491. };
  81492. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  81493. this._action = action;
  81494. };
  81495. // Define which axis you'd like to control for left & right
  81496. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  81497. switch (axis) {
  81498. case JoystickAxis.X:
  81499. case JoystickAxis.Y:
  81500. case JoystickAxis.Z:
  81501. this._axisTargetedByLeftAndRight = axis;
  81502. break;
  81503. default:
  81504. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81505. break;
  81506. }
  81507. };
  81508. // Define which axis you'd like to control for up & down
  81509. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  81510. switch (axis) {
  81511. case JoystickAxis.X:
  81512. case JoystickAxis.Y:
  81513. case JoystickAxis.Z:
  81514. this._axisTargetedByUpAndDown = axis;
  81515. break;
  81516. default:
  81517. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81518. break;
  81519. }
  81520. };
  81521. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  81522. var _this = this;
  81523. if (this.pressed) {
  81524. this._touches.forEach(function (key, touch) {
  81525. if (touch.pointerId === _this._joystickPointerID) {
  81526. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  81527. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  81528. VirtualJoystick.vjCanvasContext.beginPath();
  81529. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  81530. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81531. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  81532. VirtualJoystick.vjCanvasContext.stroke();
  81533. VirtualJoystick.vjCanvasContext.closePath();
  81534. VirtualJoystick.vjCanvasContext.beginPath();
  81535. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81536. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81537. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  81538. VirtualJoystick.vjCanvasContext.stroke();
  81539. VirtualJoystick.vjCanvasContext.closePath();
  81540. VirtualJoystick.vjCanvasContext.beginPath();
  81541. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81542. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  81543. VirtualJoystick.vjCanvasContext.stroke();
  81544. VirtualJoystick.vjCanvasContext.closePath();
  81545. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  81546. }
  81547. else {
  81548. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  81549. VirtualJoystick.vjCanvasContext.beginPath();
  81550. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  81551. VirtualJoystick.vjCanvasContext.beginPath();
  81552. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  81553. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  81554. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  81555. VirtualJoystick.vjCanvasContext.stroke();
  81556. VirtualJoystick.vjCanvasContext.closePath();
  81557. touch.prevX = touch.x;
  81558. touch.prevY = touch.y;
  81559. }
  81560. ;
  81561. });
  81562. }
  81563. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81564. };
  81565. VirtualJoystick.prototype.releaseCanvas = function () {
  81566. if (VirtualJoystick.vjCanvas) {
  81567. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  81568. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  81569. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  81570. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  81571. window.removeEventListener("resize", this._onResize);
  81572. document.body.removeChild(VirtualJoystick.vjCanvas);
  81573. VirtualJoystick.vjCanvas = null;
  81574. }
  81575. };
  81576. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  81577. VirtualJoystick._globalJoystickIndex = 0;
  81578. return VirtualJoystick;
  81579. }());
  81580. BABYLON.VirtualJoystick = VirtualJoystick;
  81581. })(BABYLON || (BABYLON = {}));
  81582. //# sourceMappingURL=babylon.virtualJoystick.js.map
  81583. var BABYLON;
  81584. (function (BABYLON) {
  81585. // We're mainly based on the logic defined into the FreeCamera code
  81586. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  81587. __extends(VirtualJoysticksCamera, _super);
  81588. function VirtualJoysticksCamera(name, position, scene) {
  81589. var _this = _super.call(this, name, position, scene) || this;
  81590. _this.inputs.addVirtualJoystick();
  81591. return _this;
  81592. }
  81593. VirtualJoysticksCamera.prototype.getClassName = function () {
  81594. return "VirtualJoysticksCamera";
  81595. };
  81596. return VirtualJoysticksCamera;
  81597. }(BABYLON.FreeCamera));
  81598. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  81599. })(BABYLON || (BABYLON = {}));
  81600. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  81601. var BABYLON;
  81602. (function (BABYLON) {
  81603. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  81604. function FreeCameraVirtualJoystickInput() {
  81605. }
  81606. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  81607. return this._leftjoystick;
  81608. };
  81609. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  81610. return this._rightjoystick;
  81611. };
  81612. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  81613. if (this._leftjoystick) {
  81614. var camera = this.camera;
  81615. var speed = camera._computeLocalCameraSpeed() * 50;
  81616. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  81617. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  81618. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  81619. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  81620. if (!this._leftjoystick.pressed) {
  81621. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  81622. }
  81623. if (!this._rightjoystick.pressed) {
  81624. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  81625. }
  81626. }
  81627. };
  81628. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  81629. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  81630. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  81631. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  81632. this._leftjoystick.setJoystickSensibility(0.15);
  81633. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  81634. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  81635. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  81636. this._rightjoystick.reverseUpDown = true;
  81637. this._rightjoystick.setJoystickSensibility(0.05);
  81638. this._rightjoystick.setJoystickColor("yellow");
  81639. };
  81640. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  81641. this._leftjoystick.releaseCanvas();
  81642. this._rightjoystick.releaseCanvas();
  81643. };
  81644. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  81645. return "FreeCameraVirtualJoystickInput";
  81646. };
  81647. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  81648. return "virtualJoystick";
  81649. };
  81650. return FreeCameraVirtualJoystickInput;
  81651. }());
  81652. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  81653. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  81654. })(BABYLON || (BABYLON = {}));
  81655. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  81656. var BABYLON;
  81657. (function (BABYLON) {
  81658. var SimplificationSettings = /** @class */ (function () {
  81659. function SimplificationSettings(quality, distance, optimizeMesh) {
  81660. this.quality = quality;
  81661. this.distance = distance;
  81662. this.optimizeMesh = optimizeMesh;
  81663. }
  81664. return SimplificationSettings;
  81665. }());
  81666. BABYLON.SimplificationSettings = SimplificationSettings;
  81667. var SimplificationQueue = /** @class */ (function () {
  81668. function SimplificationQueue() {
  81669. this.running = false;
  81670. this._simplificationArray = [];
  81671. }
  81672. SimplificationQueue.prototype.addTask = function (task) {
  81673. this._simplificationArray.push(task);
  81674. };
  81675. SimplificationQueue.prototype.executeNext = function () {
  81676. var task = this._simplificationArray.pop();
  81677. if (task) {
  81678. this.running = true;
  81679. this.runSimplification(task);
  81680. }
  81681. else {
  81682. this.running = false;
  81683. }
  81684. };
  81685. SimplificationQueue.prototype.runSimplification = function (task) {
  81686. var _this = this;
  81687. if (task.parallelProcessing) {
  81688. //parallel simplifier
  81689. task.settings.forEach(function (setting) {
  81690. var simplifier = _this.getSimplifier(task);
  81691. simplifier.simplify(setting, function (newMesh) {
  81692. task.mesh.addLODLevel(setting.distance, newMesh);
  81693. newMesh.isVisible = true;
  81694. //check if it is the last
  81695. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  81696. //all done, run the success callback.
  81697. task.successCallback();
  81698. }
  81699. _this.executeNext();
  81700. });
  81701. });
  81702. }
  81703. else {
  81704. //single simplifier.
  81705. var simplifier = this.getSimplifier(task);
  81706. var runDecimation = function (setting, callback) {
  81707. simplifier.simplify(setting, function (newMesh) {
  81708. task.mesh.addLODLevel(setting.distance, newMesh);
  81709. newMesh.isVisible = true;
  81710. //run the next quality level
  81711. callback();
  81712. });
  81713. };
  81714. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  81715. runDecimation(task.settings[loop.index], function () {
  81716. loop.executeNext();
  81717. });
  81718. }, function () {
  81719. //execution ended, run the success callback.
  81720. if (task.successCallback) {
  81721. task.successCallback();
  81722. }
  81723. _this.executeNext();
  81724. });
  81725. }
  81726. };
  81727. SimplificationQueue.prototype.getSimplifier = function (task) {
  81728. switch (task.simplificationType) {
  81729. case SimplificationType.QUADRATIC:
  81730. default:
  81731. return new QuadraticErrorSimplification(task.mesh);
  81732. }
  81733. };
  81734. return SimplificationQueue;
  81735. }());
  81736. BABYLON.SimplificationQueue = SimplificationQueue;
  81737. /**
  81738. * The implemented types of simplification.
  81739. * At the moment only Quadratic Error Decimation is implemented.
  81740. */
  81741. var SimplificationType;
  81742. (function (SimplificationType) {
  81743. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  81744. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  81745. var DecimationTriangle = /** @class */ (function () {
  81746. function DecimationTriangle(vertices) {
  81747. this.vertices = vertices;
  81748. this.error = new Array(4);
  81749. this.deleted = false;
  81750. this.isDirty = false;
  81751. this.deletePending = false;
  81752. this.borderFactor = 0;
  81753. }
  81754. return DecimationTriangle;
  81755. }());
  81756. BABYLON.DecimationTriangle = DecimationTriangle;
  81757. var DecimationVertex = /** @class */ (function () {
  81758. function DecimationVertex(position, id) {
  81759. this.position = position;
  81760. this.id = id;
  81761. this.isBorder = true;
  81762. this.q = new QuadraticMatrix();
  81763. this.triangleCount = 0;
  81764. this.triangleStart = 0;
  81765. this.originalOffsets = [];
  81766. }
  81767. DecimationVertex.prototype.updatePosition = function (newPosition) {
  81768. this.position.copyFrom(newPosition);
  81769. };
  81770. return DecimationVertex;
  81771. }());
  81772. BABYLON.DecimationVertex = DecimationVertex;
  81773. var QuadraticMatrix = /** @class */ (function () {
  81774. function QuadraticMatrix(data) {
  81775. this.data = new Array(10);
  81776. for (var i = 0; i < 10; ++i) {
  81777. if (data && data[i]) {
  81778. this.data[i] = data[i];
  81779. }
  81780. else {
  81781. this.data[i] = 0;
  81782. }
  81783. }
  81784. }
  81785. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  81786. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  81787. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  81788. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  81789. return det;
  81790. };
  81791. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  81792. for (var i = 0; i < 10; ++i) {
  81793. this.data[i] += matrix.data[i];
  81794. }
  81795. };
  81796. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  81797. for (var i = 0; i < 10; ++i) {
  81798. this.data[i] += data[i];
  81799. }
  81800. };
  81801. QuadraticMatrix.prototype.add = function (matrix) {
  81802. var m = new QuadraticMatrix();
  81803. for (var i = 0; i < 10; ++i) {
  81804. m.data[i] = this.data[i] + matrix.data[i];
  81805. }
  81806. return m;
  81807. };
  81808. QuadraticMatrix.FromData = function (a, b, c, d) {
  81809. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  81810. };
  81811. //returning an array to avoid garbage collection
  81812. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  81813. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  81814. };
  81815. return QuadraticMatrix;
  81816. }());
  81817. BABYLON.QuadraticMatrix = QuadraticMatrix;
  81818. var Reference = /** @class */ (function () {
  81819. function Reference(vertexId, triangleId) {
  81820. this.vertexId = vertexId;
  81821. this.triangleId = triangleId;
  81822. }
  81823. return Reference;
  81824. }());
  81825. BABYLON.Reference = Reference;
  81826. /**
  81827. * An implementation of the Quadratic Error simplification algorithm.
  81828. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  81829. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  81830. * @author RaananW
  81831. */
  81832. var QuadraticErrorSimplification = /** @class */ (function () {
  81833. function QuadraticErrorSimplification(_mesh) {
  81834. this._mesh = _mesh;
  81835. this.syncIterations = 5000;
  81836. this.aggressiveness = 7;
  81837. this.decimationIterations = 100;
  81838. this.boundingBoxEpsilon = BABYLON.Epsilon;
  81839. }
  81840. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  81841. var _this = this;
  81842. this.initDecimatedMesh();
  81843. //iterating through the submeshes array, one after the other.
  81844. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  81845. _this.initWithMesh(loop.index, function () {
  81846. _this.runDecimation(settings, loop.index, function () {
  81847. loop.executeNext();
  81848. });
  81849. }, settings.optimizeMesh);
  81850. }, function () {
  81851. setTimeout(function () {
  81852. successCallback(_this._reconstructedMesh);
  81853. }, 0);
  81854. });
  81855. };
  81856. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  81857. var _this = this;
  81858. var targetCount = ~~(this.triangles.length * settings.quality);
  81859. var deletedTriangles = 0;
  81860. var triangleCount = this.triangles.length;
  81861. var iterationFunction = function (iteration, callback) {
  81862. setTimeout(function () {
  81863. if (iteration % 5 === 0) {
  81864. _this.updateMesh(iteration === 0);
  81865. }
  81866. for (var i = 0; i < _this.triangles.length; ++i) {
  81867. _this.triangles[i].isDirty = false;
  81868. }
  81869. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  81870. var trianglesIterator = function (i) {
  81871. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  81872. var t = _this.triangles[tIdx];
  81873. if (!t)
  81874. return;
  81875. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  81876. return;
  81877. }
  81878. for (var j = 0; j < 3; ++j) {
  81879. if (t.error[j] < threshold) {
  81880. var deleted0 = [];
  81881. var deleted1 = [];
  81882. var v0 = t.vertices[j];
  81883. var v1 = t.vertices[(j + 1) % 3];
  81884. if (v0.isBorder || v1.isBorder)
  81885. continue;
  81886. var p = BABYLON.Vector3.Zero();
  81887. var n = BABYLON.Vector3.Zero();
  81888. var uv = BABYLON.Vector2.Zero();
  81889. var color = new BABYLON.Color4(0, 0, 0, 1);
  81890. _this.calculateError(v0, v1, p, n, uv, color);
  81891. var delTr = new Array();
  81892. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  81893. continue;
  81894. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  81895. continue;
  81896. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  81897. continue;
  81898. var uniqueArray = new Array();
  81899. delTr.forEach(function (deletedT) {
  81900. if (uniqueArray.indexOf(deletedT) === -1) {
  81901. deletedT.deletePending = true;
  81902. uniqueArray.push(deletedT);
  81903. }
  81904. });
  81905. if (uniqueArray.length % 2 !== 0) {
  81906. continue;
  81907. }
  81908. v0.q = v1.q.add(v0.q);
  81909. v0.updatePosition(p);
  81910. var tStart = _this.references.length;
  81911. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  81912. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  81913. var tCount = _this.references.length - tStart;
  81914. if (tCount <= v0.triangleCount) {
  81915. if (tCount) {
  81916. for (var c = 0; c < tCount; c++) {
  81917. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  81918. }
  81919. }
  81920. }
  81921. else {
  81922. v0.triangleStart = tStart;
  81923. }
  81924. v0.triangleCount = tCount;
  81925. break;
  81926. }
  81927. }
  81928. };
  81929. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  81930. }, 0);
  81931. };
  81932. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  81933. if (triangleCount - deletedTriangles <= targetCount)
  81934. loop.breakLoop();
  81935. else {
  81936. iterationFunction(loop.index, function () {
  81937. loop.executeNext();
  81938. });
  81939. }
  81940. }, function () {
  81941. setTimeout(function () {
  81942. //reconstruct this part of the mesh
  81943. _this.reconstructMesh(submeshIndex);
  81944. successCallback();
  81945. }, 0);
  81946. });
  81947. };
  81948. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  81949. var _this = this;
  81950. this.vertices = [];
  81951. this.triangles = [];
  81952. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  81953. var indices = this._mesh.getIndices();
  81954. var submesh = this._mesh.subMeshes[submeshIndex];
  81955. var findInVertices = function (positionToSearch) {
  81956. if (optimizeMesh) {
  81957. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  81958. if (_this.vertices[ii].position.equals(positionToSearch)) {
  81959. return _this.vertices[ii];
  81960. }
  81961. }
  81962. }
  81963. return null;
  81964. };
  81965. var vertexReferences = [];
  81966. var vertexInit = function (i) {
  81967. if (!positionData) {
  81968. return;
  81969. }
  81970. var offset = i + submesh.verticesStart;
  81971. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  81972. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  81973. vertex.originalOffsets.push(offset);
  81974. if (vertex.id === _this.vertices.length) {
  81975. _this.vertices.push(vertex);
  81976. }
  81977. vertexReferences.push(vertex.id);
  81978. };
  81979. //var totalVertices = mesh.getTotalVertices();
  81980. var totalVertices = submesh.verticesCount;
  81981. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  81982. var indicesInit = function (i) {
  81983. if (!indices) {
  81984. return;
  81985. }
  81986. var offset = (submesh.indexStart / 3) + i;
  81987. var pos = (offset * 3);
  81988. var i0 = indices[pos + 0];
  81989. var i1 = indices[pos + 1];
  81990. var i2 = indices[pos + 2];
  81991. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  81992. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  81993. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  81994. var triangle = new DecimationTriangle([v0, v1, v2]);
  81995. triangle.originalOffset = pos;
  81996. _this.triangles.push(triangle);
  81997. };
  81998. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  81999. _this.init(callback);
  82000. });
  82001. });
  82002. };
  82003. QuadraticErrorSimplification.prototype.init = function (callback) {
  82004. var _this = this;
  82005. var triangleInit1 = function (i) {
  82006. var t = _this.triangles[i];
  82007. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  82008. for (var j = 0; j < 3; j++) {
  82009. 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))));
  82010. }
  82011. };
  82012. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  82013. var triangleInit2 = function (i) {
  82014. var t = _this.triangles[i];
  82015. for (var j = 0; j < 3; ++j) {
  82016. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  82017. }
  82018. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82019. };
  82020. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  82021. callback();
  82022. });
  82023. });
  82024. };
  82025. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  82026. var newTriangles = [];
  82027. var i;
  82028. for (i = 0; i < this.vertices.length; ++i) {
  82029. this.vertices[i].triangleCount = 0;
  82030. }
  82031. var t;
  82032. var j;
  82033. for (i = 0; i < this.triangles.length; ++i) {
  82034. if (!this.triangles[i].deleted) {
  82035. t = this.triangles[i];
  82036. for (j = 0; j < 3; ++j) {
  82037. t.vertices[j].triangleCount = 1;
  82038. }
  82039. newTriangles.push(t);
  82040. }
  82041. }
  82042. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  82043. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  82044. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  82045. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  82046. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  82047. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82048. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  82049. var vertexCount = 0;
  82050. for (i = 0; i < this.vertices.length; ++i) {
  82051. var vertex = this.vertices[i];
  82052. vertex.id = vertexCount;
  82053. if (vertex.triangleCount) {
  82054. vertex.originalOffsets.forEach(function (originalOffset) {
  82055. if (!normalData) {
  82056. return;
  82057. }
  82058. newPositionData.push(vertex.position.x);
  82059. newPositionData.push(vertex.position.y);
  82060. newPositionData.push(vertex.position.z);
  82061. newNormalData.push(normalData[originalOffset * 3]);
  82062. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  82063. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  82064. if (uvs && uvs.length) {
  82065. newUVsData.push(uvs[(originalOffset * 2)]);
  82066. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  82067. }
  82068. else if (colorsData && colorsData.length) {
  82069. newColorsData.push(colorsData[(originalOffset * 4)]);
  82070. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  82071. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  82072. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  82073. }
  82074. ++vertexCount;
  82075. });
  82076. }
  82077. }
  82078. var startingIndex = this._reconstructedMesh.getTotalIndices();
  82079. var startingVertex = this._reconstructedMesh.getTotalVertices();
  82080. var submeshesArray = this._reconstructedMesh.subMeshes;
  82081. this._reconstructedMesh.subMeshes = [];
  82082. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  82083. var originalIndices = this._mesh.getIndices();
  82084. for (i = 0; i < newTriangles.length; ++i) {
  82085. t = newTriangles[i]; //now get the new referencing point for each vertex
  82086. [0, 1, 2].forEach(function (idx) {
  82087. var id = originalIndices[t.originalOffset + idx];
  82088. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  82089. if (offset < 0)
  82090. offset = 0;
  82091. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  82092. });
  82093. }
  82094. //overwriting the old vertex buffers and indices.
  82095. this._reconstructedMesh.setIndices(newIndicesArray);
  82096. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  82097. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  82098. if (newUVsData.length > 0)
  82099. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  82100. if (newColorsData.length > 0)
  82101. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  82102. //create submesh
  82103. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  82104. if (submeshIndex > 0) {
  82105. this._reconstructedMesh.subMeshes = [];
  82106. submeshesArray.forEach(function (submesh) {
  82107. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  82108. });
  82109. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  82110. }
  82111. };
  82112. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  82113. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  82114. this._reconstructedMesh.material = this._mesh.material;
  82115. this._reconstructedMesh.parent = this._mesh.parent;
  82116. this._reconstructedMesh.isVisible = false;
  82117. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  82118. };
  82119. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  82120. for (var i = 0; i < vertex1.triangleCount; ++i) {
  82121. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  82122. if (t.deleted)
  82123. continue;
  82124. var s = this.references[vertex1.triangleStart + i].vertexId;
  82125. var v1 = t.vertices[(s + 1) % 3];
  82126. var v2 = t.vertices[(s + 2) % 3];
  82127. if ((v1 === vertex2 || v2 === vertex2)) {
  82128. deletedArray[i] = true;
  82129. delTr.push(t);
  82130. continue;
  82131. }
  82132. var d1 = v1.position.subtract(point);
  82133. d1 = d1.normalize();
  82134. var d2 = v2.position.subtract(point);
  82135. d2 = d2.normalize();
  82136. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  82137. return true;
  82138. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  82139. deletedArray[i] = false;
  82140. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  82141. return true;
  82142. }
  82143. return false;
  82144. };
  82145. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  82146. var newDeleted = deletedTriangles;
  82147. for (var i = 0; i < vertex.triangleCount; ++i) {
  82148. var ref = this.references[vertex.triangleStart + i];
  82149. var t = this.triangles[ref.triangleId];
  82150. if (t.deleted)
  82151. continue;
  82152. if (deletedArray[i] && t.deletePending) {
  82153. t.deleted = true;
  82154. newDeleted++;
  82155. continue;
  82156. }
  82157. t.vertices[ref.vertexId] = origVertex;
  82158. t.isDirty = true;
  82159. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  82160. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  82161. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  82162. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82163. this.references.push(ref);
  82164. }
  82165. return newDeleted;
  82166. };
  82167. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  82168. for (var i = 0; i < this.vertices.length; ++i) {
  82169. var vCount = [];
  82170. var vId = [];
  82171. var v = this.vertices[i];
  82172. var j;
  82173. for (j = 0; j < v.triangleCount; ++j) {
  82174. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  82175. for (var ii = 0; ii < 3; ii++) {
  82176. var ofs = 0;
  82177. var vv = triangle.vertices[ii];
  82178. while (ofs < vCount.length) {
  82179. if (vId[ofs] === vv.id)
  82180. break;
  82181. ++ofs;
  82182. }
  82183. if (ofs === vCount.length) {
  82184. vCount.push(1);
  82185. vId.push(vv.id);
  82186. }
  82187. else {
  82188. vCount[ofs]++;
  82189. }
  82190. }
  82191. }
  82192. for (j = 0; j < vCount.length; ++j) {
  82193. if (vCount[j] === 1) {
  82194. this.vertices[vId[j]].isBorder = true;
  82195. }
  82196. else {
  82197. this.vertices[vId[j]].isBorder = false;
  82198. }
  82199. }
  82200. }
  82201. };
  82202. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  82203. if (identifyBorders === void 0) { identifyBorders = false; }
  82204. var i;
  82205. if (!identifyBorders) {
  82206. var newTrianglesVector = [];
  82207. for (i = 0; i < this.triangles.length; ++i) {
  82208. if (!this.triangles[i].deleted) {
  82209. newTrianglesVector.push(this.triangles[i]);
  82210. }
  82211. }
  82212. this.triangles = newTrianglesVector;
  82213. }
  82214. for (i = 0; i < this.vertices.length; ++i) {
  82215. this.vertices[i].triangleCount = 0;
  82216. this.vertices[i].triangleStart = 0;
  82217. }
  82218. var t;
  82219. var j;
  82220. var v;
  82221. for (i = 0; i < this.triangles.length; ++i) {
  82222. t = this.triangles[i];
  82223. for (j = 0; j < 3; ++j) {
  82224. v = t.vertices[j];
  82225. v.triangleCount++;
  82226. }
  82227. }
  82228. var tStart = 0;
  82229. for (i = 0; i < this.vertices.length; ++i) {
  82230. this.vertices[i].triangleStart = tStart;
  82231. tStart += this.vertices[i].triangleCount;
  82232. this.vertices[i].triangleCount = 0;
  82233. }
  82234. var newReferences = new Array(this.triangles.length * 3);
  82235. for (i = 0; i < this.triangles.length; ++i) {
  82236. t = this.triangles[i];
  82237. for (j = 0; j < 3; ++j) {
  82238. v = t.vertices[j];
  82239. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  82240. v.triangleCount++;
  82241. }
  82242. }
  82243. this.references = newReferences;
  82244. if (identifyBorders) {
  82245. this.identifyBorder();
  82246. }
  82247. };
  82248. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  82249. var x = point.x;
  82250. var y = point.y;
  82251. var z = point.z;
  82252. 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
  82253. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  82254. };
  82255. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  82256. var q = vertex1.q.add(vertex2.q);
  82257. var border = vertex1.isBorder && vertex2.isBorder;
  82258. var error = 0;
  82259. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  82260. if (qDet !== 0 && !border) {
  82261. if (!pointResult) {
  82262. pointResult = BABYLON.Vector3.Zero();
  82263. }
  82264. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  82265. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  82266. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  82267. error = this.vertexError(q, pointResult);
  82268. }
  82269. else {
  82270. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  82271. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  82272. var error1 = this.vertexError(q, vertex1.position);
  82273. var error2 = this.vertexError(q, vertex2.position);
  82274. var error3 = this.vertexError(q, p3);
  82275. error = Math.min(error1, error2, error3);
  82276. if (error === error1) {
  82277. if (pointResult) {
  82278. pointResult.copyFrom(vertex1.position);
  82279. }
  82280. }
  82281. else if (error === error2) {
  82282. if (pointResult) {
  82283. pointResult.copyFrom(vertex2.position);
  82284. }
  82285. }
  82286. else {
  82287. if (pointResult) {
  82288. pointResult.copyFrom(p3);
  82289. }
  82290. }
  82291. }
  82292. return error;
  82293. };
  82294. return QuadraticErrorSimplification;
  82295. }());
  82296. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  82297. })(BABYLON || (BABYLON = {}));
  82298. //# sourceMappingURL=babylon.meshSimplification.js.map
  82299. var BABYLON;
  82300. (function (BABYLON) {
  82301. var MeshLODLevel = /** @class */ (function () {
  82302. function MeshLODLevel(distance, mesh) {
  82303. this.distance = distance;
  82304. this.mesh = mesh;
  82305. }
  82306. return MeshLODLevel;
  82307. }());
  82308. BABYLON.MeshLODLevel = MeshLODLevel;
  82309. })(BABYLON || (BABYLON = {}));
  82310. //# sourceMappingURL=babylon.meshLODLevel.js.map
  82311. var BABYLON;
  82312. (function (BABYLON) {
  82313. /**
  82314. * Defines the root class used to create scene optimization to use with SceneOptimizer
  82315. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82316. */
  82317. var SceneOptimization = /** @class */ (function () {
  82318. /**
  82319. * Creates the SceneOptimization object
  82320. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82321. * @param desc defines the description associated with the optimization
  82322. */
  82323. function SceneOptimization(
  82324. /**
  82325. * Defines the priority of this optimization (0 by default which means first in the list)
  82326. */
  82327. priority) {
  82328. if (priority === void 0) { priority = 0; }
  82329. this.priority = priority;
  82330. }
  82331. /**
  82332. * Gets a string describing the action executed by the current optimization
  82333. * @returns description string
  82334. */
  82335. SceneOptimization.prototype.getDescription = function () {
  82336. return "";
  82337. };
  82338. /**
  82339. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82340. * @param scene defines the current scene where to apply this optimization
  82341. * @param optimizer defines the current optimizer
  82342. * @returns true if everything that can be done was applied
  82343. */
  82344. SceneOptimization.prototype.apply = function (scene, optimizer) {
  82345. return true;
  82346. };
  82347. ;
  82348. return SceneOptimization;
  82349. }());
  82350. BABYLON.SceneOptimization = SceneOptimization;
  82351. /**
  82352. * Defines an optimization used to reduce the size of render target textures
  82353. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82354. */
  82355. var TextureOptimization = /** @class */ (function (_super) {
  82356. __extends(TextureOptimization, _super);
  82357. /**
  82358. * Creates the TextureOptimization object
  82359. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82360. * @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
  82361. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82362. */
  82363. function TextureOptimization(
  82364. /**
  82365. * Defines the priority of this optimization (0 by default which means first in the list)
  82366. */
  82367. priority,
  82368. /**
  82369. * 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
  82370. */
  82371. maximumSize,
  82372. /**
  82373. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82374. */
  82375. step) {
  82376. if (priority === void 0) { priority = 0; }
  82377. if (maximumSize === void 0) { maximumSize = 1024; }
  82378. if (step === void 0) { step = 0.5; }
  82379. var _this = _super.call(this, priority) || this;
  82380. _this.priority = priority;
  82381. _this.maximumSize = maximumSize;
  82382. _this.step = step;
  82383. return _this;
  82384. }
  82385. /**
  82386. * Gets a string describing the action executed by the current optimization
  82387. * @returns description string
  82388. */
  82389. TextureOptimization.prototype.getDescription = function () {
  82390. return "Reducing render target texture size to " + this.maximumSize;
  82391. };
  82392. /**
  82393. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82394. * @param scene defines the current scene where to apply this optimization
  82395. * @param optimizer defines the current optimizer
  82396. * @returns true if everything that can be done was applied
  82397. */
  82398. TextureOptimization.prototype.apply = function (scene, optimizer) {
  82399. var allDone = true;
  82400. for (var index = 0; index < scene.textures.length; index++) {
  82401. var texture = scene.textures[index];
  82402. if (!texture.canRescale || texture.getContext) {
  82403. continue;
  82404. }
  82405. var currentSize = texture.getSize();
  82406. var maxDimension = Math.max(currentSize.width, currentSize.height);
  82407. if (maxDimension > this.maximumSize) {
  82408. texture.scale(this.step);
  82409. allDone = false;
  82410. }
  82411. }
  82412. return allDone;
  82413. };
  82414. return TextureOptimization;
  82415. }(SceneOptimization));
  82416. BABYLON.TextureOptimization = TextureOptimization;
  82417. /**
  82418. * Defines an optimization used to increase or decrease the rendering resolution
  82419. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82420. */
  82421. var HardwareScalingOptimization = /** @class */ (function (_super) {
  82422. __extends(HardwareScalingOptimization, _super);
  82423. /**
  82424. * Creates the HardwareScalingOptimization object
  82425. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82426. * @param maximumScale defines the maximum scale to use (2 by default)
  82427. * @param step defines the step to use between two passes (0.5 by default)
  82428. */
  82429. function HardwareScalingOptimization(
  82430. /**
  82431. * Defines the priority of this optimization (0 by default which means first in the list)
  82432. */
  82433. priority,
  82434. /**
  82435. * Defines the maximum scale to use (2 by default)
  82436. */
  82437. maximumScale,
  82438. /**
  82439. * Defines the step to use between two passes (0.5 by default)
  82440. */
  82441. step) {
  82442. if (priority === void 0) { priority = 0; }
  82443. if (maximumScale === void 0) { maximumScale = 2; }
  82444. if (step === void 0) { step = 0.25; }
  82445. var _this = _super.call(this, priority) || this;
  82446. _this.priority = priority;
  82447. _this.maximumScale = maximumScale;
  82448. _this.step = step;
  82449. _this._currentScale = -1;
  82450. _this._directionOffset = 1;
  82451. return _this;
  82452. }
  82453. /**
  82454. * Gets a string describing the action executed by the current optimization
  82455. * @return description string
  82456. */
  82457. HardwareScalingOptimization.prototype.getDescription = function () {
  82458. return "Setting hardware scaling level to " + this._currentScale;
  82459. };
  82460. /**
  82461. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82462. * @param scene defines the current scene where to apply this optimization
  82463. * @param optimizer defines the current optimizer
  82464. * @returns true if everything that can be done was applied
  82465. */
  82466. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  82467. if (this._currentScale === -1) {
  82468. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  82469. if (this._currentScale > this.maximumScale) {
  82470. this._directionOffset = -1;
  82471. }
  82472. }
  82473. this._currentScale += this._directionOffset * this.step;
  82474. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  82475. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  82476. };
  82477. ;
  82478. return HardwareScalingOptimization;
  82479. }(SceneOptimization));
  82480. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  82481. /**
  82482. * Defines an optimization used to remove shadows
  82483. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82484. */
  82485. var ShadowsOptimization = /** @class */ (function (_super) {
  82486. __extends(ShadowsOptimization, _super);
  82487. function ShadowsOptimization() {
  82488. return _super !== null && _super.apply(this, arguments) || this;
  82489. }
  82490. /**
  82491. * Gets a string describing the action executed by the current optimization
  82492. * @return description string
  82493. */
  82494. ShadowsOptimization.prototype.getDescription = function () {
  82495. return "Turning shadows on/off";
  82496. };
  82497. /**
  82498. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82499. * @param scene defines the current scene where to apply this optimization
  82500. * @param optimizer defines the current optimizer
  82501. * @returns true if everything that can be done was applied
  82502. */
  82503. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  82504. scene.shadowsEnabled = optimizer.isInImprovementMode;
  82505. return true;
  82506. };
  82507. ;
  82508. return ShadowsOptimization;
  82509. }(SceneOptimization));
  82510. BABYLON.ShadowsOptimization = ShadowsOptimization;
  82511. /**
  82512. * Defines an optimization used to turn post-processes off
  82513. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82514. */
  82515. var PostProcessesOptimization = /** @class */ (function (_super) {
  82516. __extends(PostProcessesOptimization, _super);
  82517. function PostProcessesOptimization() {
  82518. return _super !== null && _super.apply(this, arguments) || this;
  82519. }
  82520. /**
  82521. * Gets a string describing the action executed by the current optimization
  82522. * @return description string
  82523. */
  82524. PostProcessesOptimization.prototype.getDescription = function () {
  82525. return "Turning post-processes on/off";
  82526. };
  82527. /**
  82528. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82529. * @param scene defines the current scene where to apply this optimization
  82530. * @param optimizer defines the current optimizer
  82531. * @returns true if everything that can be done was applied
  82532. */
  82533. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  82534. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  82535. return true;
  82536. };
  82537. ;
  82538. return PostProcessesOptimization;
  82539. }(SceneOptimization));
  82540. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  82541. /**
  82542. * Defines an optimization used to turn lens flares off
  82543. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82544. */
  82545. var LensFlaresOptimization = /** @class */ (function (_super) {
  82546. __extends(LensFlaresOptimization, _super);
  82547. function LensFlaresOptimization() {
  82548. return _super !== null && _super.apply(this, arguments) || this;
  82549. }
  82550. /**
  82551. * Gets a string describing the action executed by the current optimization
  82552. * @return description string
  82553. */
  82554. LensFlaresOptimization.prototype.getDescription = function () {
  82555. return "Turning lens flares on/off";
  82556. };
  82557. /**
  82558. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82559. * @param scene defines the current scene where to apply this optimization
  82560. * @param optimizer defines the current optimizer
  82561. * @returns true if everything that can be done was applied
  82562. */
  82563. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  82564. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  82565. return true;
  82566. };
  82567. ;
  82568. return LensFlaresOptimization;
  82569. }(SceneOptimization));
  82570. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  82571. /**
  82572. * Defines an optimization based on user defined callback.
  82573. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82574. */
  82575. var CustomOptimization = /** @class */ (function (_super) {
  82576. __extends(CustomOptimization, _super);
  82577. function CustomOptimization() {
  82578. return _super !== null && _super.apply(this, arguments) || this;
  82579. }
  82580. /**
  82581. * Gets a string describing the action executed by the current optimization
  82582. * @returns description string
  82583. */
  82584. CustomOptimization.prototype.getDescription = function () {
  82585. if (this.onGetDescription) {
  82586. return this.onGetDescription();
  82587. }
  82588. return "Running user defined callback";
  82589. };
  82590. /**
  82591. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82592. * @param scene defines the current scene where to apply this optimization
  82593. * @param optimizer defines the current optimizer
  82594. * @returns true if everything that can be done was applied
  82595. */
  82596. CustomOptimization.prototype.apply = function (scene, optimizer) {
  82597. if (this.onApply) {
  82598. return this.onApply(scene, optimizer);
  82599. }
  82600. return true;
  82601. };
  82602. ;
  82603. return CustomOptimization;
  82604. }(SceneOptimization));
  82605. BABYLON.CustomOptimization = CustomOptimization;
  82606. /**
  82607. * Defines an optimization used to turn particles off
  82608. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82609. */
  82610. var ParticlesOptimization = /** @class */ (function (_super) {
  82611. __extends(ParticlesOptimization, _super);
  82612. function ParticlesOptimization() {
  82613. return _super !== null && _super.apply(this, arguments) || this;
  82614. }
  82615. /**
  82616. * Gets a string describing the action executed by the current optimization
  82617. * @return description string
  82618. */
  82619. ParticlesOptimization.prototype.getDescription = function () {
  82620. return "Turning particles on/off";
  82621. };
  82622. /**
  82623. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82624. * @param scene defines the current scene where to apply this optimization
  82625. * @param optimizer defines the current optimizer
  82626. * @returns true if everything that can be done was applied
  82627. */
  82628. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  82629. scene.particlesEnabled = optimizer.isInImprovementMode;
  82630. return true;
  82631. };
  82632. ;
  82633. return ParticlesOptimization;
  82634. }(SceneOptimization));
  82635. BABYLON.ParticlesOptimization = ParticlesOptimization;
  82636. /**
  82637. * Defines an optimization used to turn render targets off
  82638. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82639. */
  82640. var RenderTargetsOptimization = /** @class */ (function (_super) {
  82641. __extends(RenderTargetsOptimization, _super);
  82642. function RenderTargetsOptimization() {
  82643. return _super !== null && _super.apply(this, arguments) || this;
  82644. }
  82645. /**
  82646. * Gets a string describing the action executed by the current optimization
  82647. * @return description string
  82648. */
  82649. RenderTargetsOptimization.prototype.getDescription = function () {
  82650. return "Turning render targets off";
  82651. };
  82652. /**
  82653. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82654. * @param scene defines the current scene where to apply this optimization
  82655. * @param optimizer defines the current optimizer
  82656. * @returns true if everything that can be done was applied
  82657. */
  82658. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  82659. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  82660. return true;
  82661. };
  82662. ;
  82663. return RenderTargetsOptimization;
  82664. }(SceneOptimization));
  82665. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  82666. /**
  82667. * Defines an optimization used to merge meshes with compatible materials
  82668. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82669. */
  82670. var MergeMeshesOptimization = /** @class */ (function (_super) {
  82671. __extends(MergeMeshesOptimization, _super);
  82672. function MergeMeshesOptimization() {
  82673. var _this = _super !== null && _super.apply(this, arguments) || this;
  82674. _this._canBeMerged = function (abstractMesh) {
  82675. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  82676. return false;
  82677. }
  82678. var mesh = abstractMesh;
  82679. if (!mesh.isVisible || !mesh.isEnabled()) {
  82680. return false;
  82681. }
  82682. if (mesh.instances.length > 0) {
  82683. return false;
  82684. }
  82685. if (mesh.skeleton || mesh.hasLODLevels) {
  82686. return false;
  82687. }
  82688. if (mesh.parent) {
  82689. return false;
  82690. }
  82691. return true;
  82692. };
  82693. return _this;
  82694. }
  82695. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  82696. /**
  82697. * Gets or sets a boolean which defines if optimization octree has to be updated
  82698. */
  82699. get: function () {
  82700. return MergeMeshesOptimization._UpdateSelectionTree;
  82701. },
  82702. /**
  82703. * Gets or sets a boolean which defines if optimization octree has to be updated
  82704. */
  82705. set: function (value) {
  82706. MergeMeshesOptimization._UpdateSelectionTree = value;
  82707. },
  82708. enumerable: true,
  82709. configurable: true
  82710. });
  82711. /**
  82712. * Gets a string describing the action executed by the current optimization
  82713. * @return description string
  82714. */
  82715. MergeMeshesOptimization.prototype.getDescription = function () {
  82716. return "Merging similar meshes together";
  82717. };
  82718. /**
  82719. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82720. * @param scene defines the current scene where to apply this optimization
  82721. * @param optimizer defines the current optimizer
  82722. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  82723. * @returns true if everything that can be done was applied
  82724. */
  82725. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  82726. var globalPool = scene.meshes.slice(0);
  82727. var globalLength = globalPool.length;
  82728. for (var index = 0; index < globalLength; index++) {
  82729. var currentPool = new Array();
  82730. var current = globalPool[index];
  82731. // Checks
  82732. if (!this._canBeMerged(current)) {
  82733. continue;
  82734. }
  82735. currentPool.push(current);
  82736. // Find compatible meshes
  82737. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  82738. var otherMesh = globalPool[subIndex];
  82739. if (!this._canBeMerged(otherMesh)) {
  82740. continue;
  82741. }
  82742. if (otherMesh.material !== current.material) {
  82743. continue;
  82744. }
  82745. if (otherMesh.checkCollisions !== current.checkCollisions) {
  82746. continue;
  82747. }
  82748. currentPool.push(otherMesh);
  82749. globalLength--;
  82750. globalPool.splice(subIndex, 1);
  82751. subIndex--;
  82752. }
  82753. if (currentPool.length < 2) {
  82754. continue;
  82755. }
  82756. // Merge meshes
  82757. BABYLON.Mesh.MergeMeshes(currentPool);
  82758. }
  82759. if (updateSelectionTree != undefined) {
  82760. if (updateSelectionTree) {
  82761. scene.createOrUpdateSelectionOctree();
  82762. }
  82763. }
  82764. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  82765. scene.createOrUpdateSelectionOctree();
  82766. }
  82767. return true;
  82768. };
  82769. ;
  82770. MergeMeshesOptimization._UpdateSelectionTree = false;
  82771. return MergeMeshesOptimization;
  82772. }(SceneOptimization));
  82773. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  82774. /**
  82775. * Defines a list of options used by SceneOptimizer
  82776. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82777. */
  82778. var SceneOptimizerOptions = /** @class */ (function () {
  82779. /**
  82780. * Creates a new list of options used by SceneOptimizer
  82781. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  82782. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  82783. */
  82784. function SceneOptimizerOptions(
  82785. /**
  82786. * Defines the target frame rate to reach (60 by default)
  82787. */
  82788. targetFrameRate,
  82789. /**
  82790. * Defines the interval between two checkes (2000ms by default)
  82791. */
  82792. trackerDuration) {
  82793. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  82794. if (trackerDuration === void 0) { trackerDuration = 2000; }
  82795. this.targetFrameRate = targetFrameRate;
  82796. this.trackerDuration = trackerDuration;
  82797. /**
  82798. * Gets the list of optimizations to apply
  82799. */
  82800. this.optimizations = new Array();
  82801. }
  82802. /**
  82803. * Add a new optimization
  82804. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  82805. * @returns the current SceneOptimizerOptions
  82806. */
  82807. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  82808. this.optimizations.push(optimization);
  82809. return this;
  82810. };
  82811. /**
  82812. * Add a new custom optimization
  82813. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  82814. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  82815. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82816. * @returns the current SceneOptimizerOptions
  82817. */
  82818. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  82819. if (priority === void 0) { priority = 0; }
  82820. var optimization = new CustomOptimization(priority);
  82821. optimization.onApply = onApply;
  82822. optimization.onGetDescription = onGetDescription;
  82823. this.optimizations.push(optimization);
  82824. return this;
  82825. };
  82826. /**
  82827. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  82828. * @param targetFrameRate defines the target frame rate (60 by default)
  82829. * @returns a SceneOptimizerOptions object
  82830. */
  82831. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  82832. var result = new SceneOptimizerOptions(targetFrameRate);
  82833. var priority = 0;
  82834. result.addOptimization(new MergeMeshesOptimization(priority));
  82835. result.addOptimization(new ShadowsOptimization(priority));
  82836. result.addOptimization(new LensFlaresOptimization(priority));
  82837. // Next priority
  82838. priority++;
  82839. result.addOptimization(new PostProcessesOptimization(priority));
  82840. result.addOptimization(new ParticlesOptimization(priority));
  82841. // Next priority
  82842. priority++;
  82843. result.addOptimization(new TextureOptimization(priority, 1024));
  82844. return result;
  82845. };
  82846. /**
  82847. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  82848. * @param targetFrameRate defines the target frame rate (60 by default)
  82849. * @returns a SceneOptimizerOptions object
  82850. */
  82851. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  82852. var result = new SceneOptimizerOptions(targetFrameRate);
  82853. var priority = 0;
  82854. result.addOptimization(new MergeMeshesOptimization(priority));
  82855. result.addOptimization(new ShadowsOptimization(priority));
  82856. result.addOptimization(new LensFlaresOptimization(priority));
  82857. // Next priority
  82858. priority++;
  82859. result.addOptimization(new PostProcessesOptimization(priority));
  82860. result.addOptimization(new ParticlesOptimization(priority));
  82861. // Next priority
  82862. priority++;
  82863. result.addOptimization(new TextureOptimization(priority, 512));
  82864. // Next priority
  82865. priority++;
  82866. result.addOptimization(new RenderTargetsOptimization(priority));
  82867. // Next priority
  82868. priority++;
  82869. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  82870. return result;
  82871. };
  82872. /**
  82873. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  82874. * @param targetFrameRate defines the target frame rate (60 by default)
  82875. * @returns a SceneOptimizerOptions object
  82876. */
  82877. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  82878. var result = new SceneOptimizerOptions(targetFrameRate);
  82879. var priority = 0;
  82880. result.addOptimization(new MergeMeshesOptimization(priority));
  82881. result.addOptimization(new ShadowsOptimization(priority));
  82882. result.addOptimization(new LensFlaresOptimization(priority));
  82883. // Next priority
  82884. priority++;
  82885. result.addOptimization(new PostProcessesOptimization(priority));
  82886. result.addOptimization(new ParticlesOptimization(priority));
  82887. // Next priority
  82888. priority++;
  82889. result.addOptimization(new TextureOptimization(priority, 256));
  82890. // Next priority
  82891. priority++;
  82892. result.addOptimization(new RenderTargetsOptimization(priority));
  82893. // Next priority
  82894. priority++;
  82895. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  82896. return result;
  82897. };
  82898. return SceneOptimizerOptions;
  82899. }());
  82900. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  82901. /**
  82902. * Class used to run optimizations in order to reach a target frame rate
  82903. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82904. */
  82905. var SceneOptimizer = /** @class */ (function () {
  82906. /**
  82907. * Creates a new SceneOptimizer
  82908. * @param scene defines the scene to work on
  82909. * @param options defines the options to use with the SceneOptimizer
  82910. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  82911. * @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)
  82912. */
  82913. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  82914. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  82915. if (improvementMode === void 0) { improvementMode = false; }
  82916. var _this = this;
  82917. this._isRunning = false;
  82918. this._currentPriorityLevel = 0;
  82919. this._targetFrameRate = 60;
  82920. this._trackerDuration = 2000;
  82921. this._currentFrameRate = 0;
  82922. this._improvementMode = false;
  82923. /**
  82924. * Defines an observable called when the optimizer reaches the target frame rate
  82925. */
  82926. this.onSuccessObservable = new BABYLON.Observable();
  82927. /**
  82928. * Defines an observable called when the optimizer enables an optimization
  82929. */
  82930. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  82931. /**
  82932. * Defines an observable called when the optimizer is not able to reach the target frame rate
  82933. */
  82934. this.onFailureObservable = new BABYLON.Observable();
  82935. if (!options) {
  82936. this._options = new SceneOptimizerOptions();
  82937. }
  82938. else {
  82939. this._options = options;
  82940. }
  82941. if (this._options.targetFrameRate) {
  82942. this._targetFrameRate = this._options.targetFrameRate;
  82943. }
  82944. if (this._options.trackerDuration) {
  82945. this._trackerDuration = this._options.trackerDuration;
  82946. }
  82947. if (autoGeneratePriorities) {
  82948. var priority = 0;
  82949. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  82950. var optim = _a[_i];
  82951. optim.priority = priority++;
  82952. }
  82953. }
  82954. this._improvementMode = improvementMode;
  82955. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82956. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  82957. _this._sceneDisposeObserver = null;
  82958. _this.dispose();
  82959. });
  82960. }
  82961. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  82962. /**
  82963. * Gets a boolean indicating if the optimizer is in improvement mode
  82964. */
  82965. get: function () {
  82966. return this._improvementMode;
  82967. },
  82968. enumerable: true,
  82969. configurable: true
  82970. });
  82971. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  82972. /**
  82973. * Gets the current priority level (0 at start)
  82974. */
  82975. get: function () {
  82976. return this._currentPriorityLevel;
  82977. },
  82978. enumerable: true,
  82979. configurable: true
  82980. });
  82981. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  82982. /**
  82983. * Gets the current frame rate checked by the SceneOptimizer
  82984. */
  82985. get: function () {
  82986. return this._currentFrameRate;
  82987. },
  82988. enumerable: true,
  82989. configurable: true
  82990. });
  82991. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  82992. /**
  82993. * Gets or sets the current target frame rate (60 by default)
  82994. */
  82995. get: function () {
  82996. return this._targetFrameRate;
  82997. },
  82998. /**
  82999. * Gets or sets the current target frame rate (60 by default)
  83000. */
  83001. set: function (value) {
  83002. this._targetFrameRate = value;
  83003. },
  83004. enumerable: true,
  83005. configurable: true
  83006. });
  83007. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  83008. /**
  83009. * Gets or sets the current interval between two checks (every 2000ms by default)
  83010. */
  83011. get: function () {
  83012. return this._trackerDuration;
  83013. },
  83014. /**
  83015. * Gets or sets the current interval between two checks (every 2000ms by default)
  83016. */
  83017. set: function (value) {
  83018. this._trackerDuration = value;
  83019. },
  83020. enumerable: true,
  83021. configurable: true
  83022. });
  83023. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  83024. /**
  83025. * Gets the list of active optimizations
  83026. */
  83027. get: function () {
  83028. return this._options.optimizations;
  83029. },
  83030. enumerable: true,
  83031. configurable: true
  83032. });
  83033. /**
  83034. * Stops the current optimizer
  83035. */
  83036. SceneOptimizer.prototype.stop = function () {
  83037. this._isRunning = false;
  83038. };
  83039. /**
  83040. * Reset the optimizer to initial step (current priority level = 0)
  83041. */
  83042. SceneOptimizer.prototype.reset = function () {
  83043. this._currentPriorityLevel = 0;
  83044. };
  83045. /**
  83046. * Start the optimizer. By default it will try to reach a specific framerate
  83047. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  83048. */
  83049. SceneOptimizer.prototype.start = function () {
  83050. var _this = this;
  83051. if (this._isRunning) {
  83052. return;
  83053. }
  83054. this._isRunning = true;
  83055. // Let's wait for the scene to be ready before running our check
  83056. this._scene.executeWhenReady(function () {
  83057. setTimeout(function () {
  83058. _this._checkCurrentState();
  83059. }, _this._trackerDuration);
  83060. });
  83061. };
  83062. SceneOptimizer.prototype._checkCurrentState = function () {
  83063. var _this = this;
  83064. if (!this._isRunning) {
  83065. return;
  83066. }
  83067. var scene = this._scene;
  83068. var options = this._options;
  83069. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  83070. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  83071. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  83072. this._isRunning = false;
  83073. this.onSuccessObservable.notifyObservers(this);
  83074. return;
  83075. }
  83076. // Apply current level of optimizations
  83077. var allDone = true;
  83078. var noOptimizationApplied = true;
  83079. for (var index = 0; index < options.optimizations.length; index++) {
  83080. var optimization = options.optimizations[index];
  83081. if (optimization.priority === this._currentPriorityLevel) {
  83082. noOptimizationApplied = false;
  83083. allDone = allDone && optimization.apply(scene, this);
  83084. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  83085. }
  83086. }
  83087. // If no optimization was applied, this is a failure :(
  83088. if (noOptimizationApplied) {
  83089. this._isRunning = false;
  83090. this.onFailureObservable.notifyObservers(this);
  83091. return;
  83092. }
  83093. // If all optimizations were done, move to next level
  83094. if (allDone) {
  83095. this._currentPriorityLevel++;
  83096. }
  83097. // Let's the system running for a specific amount of time before checking FPS
  83098. scene.executeWhenReady(function () {
  83099. setTimeout(function () {
  83100. _this._checkCurrentState();
  83101. }, _this._trackerDuration);
  83102. });
  83103. };
  83104. /**
  83105. * Release all resources
  83106. */
  83107. SceneOptimizer.prototype.dispose = function () {
  83108. this.stop();
  83109. this.onSuccessObservable.clear();
  83110. this.onFailureObservable.clear();
  83111. this.onNewOptimizationAppliedObservable.clear();
  83112. if (this._sceneDisposeObserver) {
  83113. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  83114. }
  83115. };
  83116. /**
  83117. * Helper function to create a SceneOptimizer with one single line of code
  83118. * @param scene defines the scene to work on
  83119. * @param options defines the options to use with the SceneOptimizer
  83120. * @param onSuccess defines a callback to call on success
  83121. * @param onFailure defines a callback to call on failure
  83122. * @returns the new SceneOptimizer object
  83123. */
  83124. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  83125. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  83126. if (onSuccess) {
  83127. optimizer.onSuccessObservable.add(function () {
  83128. onSuccess();
  83129. });
  83130. }
  83131. if (onFailure) {
  83132. optimizer.onFailureObservable.add(function () {
  83133. onFailure();
  83134. });
  83135. }
  83136. optimizer.start();
  83137. return optimizer;
  83138. };
  83139. return SceneOptimizer;
  83140. }());
  83141. BABYLON.SceneOptimizer = SceneOptimizer;
  83142. })(BABYLON || (BABYLON = {}));
  83143. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  83144. var BABYLON;
  83145. (function (BABYLON) {
  83146. var OutlineRenderer = /** @class */ (function () {
  83147. function OutlineRenderer(scene) {
  83148. this.zOffset = 1;
  83149. this._scene = scene;
  83150. }
  83151. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  83152. var _this = this;
  83153. if (useOverlay === void 0) { useOverlay = false; }
  83154. var scene = this._scene;
  83155. var engine = this._scene.getEngine();
  83156. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83157. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  83158. return;
  83159. }
  83160. var mesh = subMesh.getRenderingMesh();
  83161. var material = subMesh.getMaterial();
  83162. if (!material || !scene.activeCamera) {
  83163. return;
  83164. }
  83165. engine.enableEffect(this._effect);
  83166. // Logarithmic depth
  83167. if (material.useLogarithmicDepth) {
  83168. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  83169. }
  83170. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  83171. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  83172. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83173. // Bones
  83174. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83175. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83176. }
  83177. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  83178. // Alpha test
  83179. if (material && material.needAlphaTesting()) {
  83180. var alphaTexture = material.getAlphaTestTexture();
  83181. if (alphaTexture) {
  83182. this._effect.setTexture("diffuseSampler", alphaTexture);
  83183. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83184. }
  83185. }
  83186. engine.setZOffset(-this.zOffset);
  83187. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  83188. engine.setZOffset(0);
  83189. };
  83190. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  83191. var defines = [];
  83192. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83193. var mesh = subMesh.getMesh();
  83194. var material = subMesh.getMaterial();
  83195. if (material) {
  83196. // Alpha test
  83197. if (material.needAlphaTesting()) {
  83198. defines.push("#define ALPHATEST");
  83199. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83200. attribs.push(BABYLON.VertexBuffer.UVKind);
  83201. defines.push("#define UV1");
  83202. }
  83203. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83204. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83205. defines.push("#define UV2");
  83206. }
  83207. }
  83208. //Logarithmic depth
  83209. if (material.useLogarithmicDepth) {
  83210. defines.push("#define LOGARITHMICDEPTH");
  83211. }
  83212. }
  83213. // Bones
  83214. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83215. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83216. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83217. if (mesh.numBoneInfluencers > 4) {
  83218. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83219. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83220. }
  83221. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83222. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83223. }
  83224. else {
  83225. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83226. }
  83227. // Instances
  83228. if (useInstances) {
  83229. defines.push("#define INSTANCES");
  83230. attribs.push("world0");
  83231. attribs.push("world1");
  83232. attribs.push("world2");
  83233. attribs.push("world3");
  83234. }
  83235. // Get correct effect
  83236. var join = defines.join("\n");
  83237. if (this._cachedDefines !== join) {
  83238. this._cachedDefines = join;
  83239. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  83240. }
  83241. return this._effect.isReady();
  83242. };
  83243. return OutlineRenderer;
  83244. }());
  83245. BABYLON.OutlineRenderer = OutlineRenderer;
  83246. })(BABYLON || (BABYLON = {}));
  83247. //# sourceMappingURL=babylon.outlineRenderer.js.map
  83248. var BABYLON;
  83249. (function (BABYLON) {
  83250. var FaceAdjacencies = /** @class */ (function () {
  83251. function FaceAdjacencies() {
  83252. this.edges = new Array();
  83253. this.edgesConnectedCount = 0;
  83254. }
  83255. return FaceAdjacencies;
  83256. }());
  83257. var EdgesRenderer = /** @class */ (function () {
  83258. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  83259. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  83260. if (epsilon === void 0) { epsilon = 0.95; }
  83261. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  83262. this.edgesWidthScalerForOrthographic = 1000.0;
  83263. this.edgesWidthScalerForPerspective = 50.0;
  83264. this._linesPositions = new Array();
  83265. this._linesNormals = new Array();
  83266. this._linesIndices = new Array();
  83267. this._buffers = {};
  83268. this._checkVerticesInsteadOfIndices = false;
  83269. this._source = source;
  83270. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  83271. this._epsilon = epsilon;
  83272. this._prepareRessources();
  83273. this._generateEdgesLines();
  83274. }
  83275. EdgesRenderer.prototype._prepareRessources = function () {
  83276. if (this._lineShader) {
  83277. return;
  83278. }
  83279. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  83280. attributes: ["position", "normal"],
  83281. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  83282. });
  83283. this._lineShader.disableDepthWrite = true;
  83284. this._lineShader.backFaceCulling = false;
  83285. };
  83286. EdgesRenderer.prototype._rebuild = function () {
  83287. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83288. if (buffer) {
  83289. buffer._rebuild();
  83290. }
  83291. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83292. if (buffer) {
  83293. buffer._rebuild();
  83294. }
  83295. var scene = this._source.getScene();
  83296. var engine = scene.getEngine();
  83297. this._ib = engine.createIndexBuffer(this._linesIndices);
  83298. };
  83299. EdgesRenderer.prototype.dispose = function () {
  83300. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83301. if (buffer) {
  83302. buffer.dispose();
  83303. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  83304. }
  83305. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83306. if (buffer) {
  83307. buffer.dispose();
  83308. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  83309. }
  83310. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  83311. this._lineShader.dispose();
  83312. };
  83313. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  83314. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  83315. return 0;
  83316. }
  83317. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  83318. return 1;
  83319. }
  83320. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  83321. return 2;
  83322. }
  83323. return -1;
  83324. };
  83325. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  83326. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  83327. return 0;
  83328. }
  83329. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  83330. return 1;
  83331. }
  83332. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  83333. return 2;
  83334. }
  83335. return -1;
  83336. };
  83337. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  83338. var needToCreateLine;
  83339. if (edge === undefined) {
  83340. needToCreateLine = true;
  83341. }
  83342. else {
  83343. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  83344. needToCreateLine = dotProduct < this._epsilon;
  83345. }
  83346. if (needToCreateLine) {
  83347. var offset = this._linesPositions.length / 3;
  83348. var normal = p0.subtract(p1);
  83349. normal.normalize();
  83350. // Positions
  83351. this._linesPositions.push(p0.x);
  83352. this._linesPositions.push(p0.y);
  83353. this._linesPositions.push(p0.z);
  83354. this._linesPositions.push(p0.x);
  83355. this._linesPositions.push(p0.y);
  83356. this._linesPositions.push(p0.z);
  83357. this._linesPositions.push(p1.x);
  83358. this._linesPositions.push(p1.y);
  83359. this._linesPositions.push(p1.z);
  83360. this._linesPositions.push(p1.x);
  83361. this._linesPositions.push(p1.y);
  83362. this._linesPositions.push(p1.z);
  83363. // Normals
  83364. this._linesNormals.push(p1.x);
  83365. this._linesNormals.push(p1.y);
  83366. this._linesNormals.push(p1.z);
  83367. this._linesNormals.push(-1);
  83368. this._linesNormals.push(p1.x);
  83369. this._linesNormals.push(p1.y);
  83370. this._linesNormals.push(p1.z);
  83371. this._linesNormals.push(1);
  83372. this._linesNormals.push(p0.x);
  83373. this._linesNormals.push(p0.y);
  83374. this._linesNormals.push(p0.z);
  83375. this._linesNormals.push(-1);
  83376. this._linesNormals.push(p0.x);
  83377. this._linesNormals.push(p0.y);
  83378. this._linesNormals.push(p0.z);
  83379. this._linesNormals.push(1);
  83380. // Indices
  83381. this._linesIndices.push(offset);
  83382. this._linesIndices.push(offset + 1);
  83383. this._linesIndices.push(offset + 2);
  83384. this._linesIndices.push(offset);
  83385. this._linesIndices.push(offset + 2);
  83386. this._linesIndices.push(offset + 3);
  83387. }
  83388. };
  83389. EdgesRenderer.prototype._generateEdgesLines = function () {
  83390. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83391. var indices = this._source.getIndices();
  83392. if (!indices || !positions) {
  83393. return;
  83394. }
  83395. // First let's find adjacencies
  83396. var adjacencies = new Array();
  83397. var faceNormals = new Array();
  83398. var index;
  83399. var faceAdjacencies;
  83400. // Prepare faces
  83401. for (index = 0; index < indices.length; index += 3) {
  83402. faceAdjacencies = new FaceAdjacencies();
  83403. var p0Index = indices[index];
  83404. var p1Index = indices[index + 1];
  83405. var p2Index = indices[index + 2];
  83406. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  83407. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  83408. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  83409. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  83410. faceNormal.normalize();
  83411. faceNormals.push(faceNormal);
  83412. adjacencies.push(faceAdjacencies);
  83413. }
  83414. // Scan
  83415. for (index = 0; index < adjacencies.length; index++) {
  83416. faceAdjacencies = adjacencies[index];
  83417. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  83418. var otherFaceAdjacencies = adjacencies[otherIndex];
  83419. if (faceAdjacencies.edgesConnectedCount === 3) {
  83420. break;
  83421. }
  83422. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  83423. continue;
  83424. }
  83425. var otherP0 = indices[otherIndex * 3];
  83426. var otherP1 = indices[otherIndex * 3 + 1];
  83427. var otherP2 = indices[otherIndex * 3 + 2];
  83428. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  83429. var otherEdgeIndex = 0;
  83430. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  83431. continue;
  83432. }
  83433. switch (edgeIndex) {
  83434. case 0:
  83435. if (this._checkVerticesInsteadOfIndices) {
  83436. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83437. }
  83438. else {
  83439. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  83440. }
  83441. break;
  83442. case 1:
  83443. if (this._checkVerticesInsteadOfIndices) {
  83444. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83445. }
  83446. else {
  83447. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  83448. }
  83449. break;
  83450. case 2:
  83451. if (this._checkVerticesInsteadOfIndices) {
  83452. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83453. }
  83454. else {
  83455. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  83456. }
  83457. break;
  83458. }
  83459. if (otherEdgeIndex === -1) {
  83460. continue;
  83461. }
  83462. faceAdjacencies.edges[edgeIndex] = otherIndex;
  83463. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  83464. faceAdjacencies.edgesConnectedCount++;
  83465. otherFaceAdjacencies.edgesConnectedCount++;
  83466. if (faceAdjacencies.edgesConnectedCount === 3) {
  83467. break;
  83468. }
  83469. }
  83470. }
  83471. }
  83472. // Create lines
  83473. for (index = 0; index < adjacencies.length; index++) {
  83474. // 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
  83475. var current = adjacencies[index];
  83476. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  83477. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  83478. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  83479. }
  83480. // Merge into a single mesh
  83481. var engine = this._source.getScene().getEngine();
  83482. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  83483. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  83484. this._ib = engine.createIndexBuffer(this._linesIndices);
  83485. this._indicesCount = this._linesIndices.length;
  83486. };
  83487. EdgesRenderer.prototype.render = function () {
  83488. var scene = this._source.getScene();
  83489. if (!this._lineShader.isReady() || !scene.activeCamera) {
  83490. return;
  83491. }
  83492. var engine = scene.getEngine();
  83493. this._lineShader._preBind();
  83494. // VBOs
  83495. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  83496. scene.resetCachedMaterial();
  83497. this._lineShader.setColor4("color", this._source.edgesColor);
  83498. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  83499. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  83500. }
  83501. else {
  83502. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  83503. }
  83504. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  83505. this._lineShader.bind(this._source.getWorldMatrix());
  83506. // Draw order
  83507. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  83508. this._lineShader.unbind();
  83509. engine.setDepthWrite(true);
  83510. };
  83511. return EdgesRenderer;
  83512. }());
  83513. BABYLON.EdgesRenderer = EdgesRenderer;
  83514. })(BABYLON || (BABYLON = {}));
  83515. //# sourceMappingURL=babylon.edgesRenderer.js.map
  83516. var __assign = (this && this.__assign) || Object.assign || function(t) {
  83517. for (var s, i = 1, n = arguments.length; i < n; i++) {
  83518. s = arguments[i];
  83519. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  83520. t[p] = s[p];
  83521. }
  83522. return t;
  83523. };
  83524. var BABYLON;
  83525. (function (BABYLON) {
  83526. /**
  83527. * The effect layer Helps adding post process effect blended with the main pass.
  83528. *
  83529. * This can be for instance use to generate glow or higlight effects on the scene.
  83530. *
  83531. * The effect layer class can not be used directly and is intented to inherited from to be
  83532. * customized per effects.
  83533. */
  83534. var EffectLayer = /** @class */ (function () {
  83535. /**
  83536. * Instantiates a new effect Layer and references it in the scene.
  83537. * @param name The name of the layer
  83538. * @param scene The scene to use the layer in
  83539. */
  83540. function EffectLayer(
  83541. /** The Friendly of the effect in the scene */
  83542. name, scene) {
  83543. this.name = name;
  83544. this._vertexBuffers = {};
  83545. this._maxSize = 0;
  83546. this._mainTextureDesiredSize = { width: 0, height: 0 };
  83547. this._shouldRender = true;
  83548. this._postProcesses = [];
  83549. this._textures = [];
  83550. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  83551. /**
  83552. * The clear color of the texture used to generate the glow map.
  83553. */
  83554. this.neutralColor = new BABYLON.Color4();
  83555. /**
  83556. * Specifies wether the highlight layer is enabled or not.
  83557. */
  83558. this.isEnabled = true;
  83559. /**
  83560. * An event triggered when the effect layer has been disposed.
  83561. */
  83562. this.onDisposeObservable = new BABYLON.Observable();
  83563. /**
  83564. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  83565. */
  83566. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  83567. /**
  83568. * An event triggered when the generated texture is being merged in the scene.
  83569. */
  83570. this.onBeforeComposeObservable = new BABYLON.Observable();
  83571. /**
  83572. * An event triggered when the generated texture has been merged in the scene.
  83573. */
  83574. this.onAfterComposeObservable = new BABYLON.Observable();
  83575. /**
  83576. * An event triggered when the efffect layer changes its size.
  83577. */
  83578. this.onSizeChangedObservable = new BABYLON.Observable();
  83579. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83580. this._engine = scene.getEngine();
  83581. this._maxSize = this._engine.getCaps().maxTextureSize;
  83582. this._scene.effectLayers.push(this);
  83583. // Generate Buffers
  83584. this._generateIndexBuffer();
  83585. this._genrateVertexBuffer();
  83586. }
  83587. Object.defineProperty(EffectLayer.prototype, "camera", {
  83588. /**
  83589. * Gets the camera attached to the layer.
  83590. */
  83591. get: function () {
  83592. return this._effectLayerOptions.camera;
  83593. },
  83594. enumerable: true,
  83595. configurable: true
  83596. });
  83597. /**
  83598. * Initializes the effect layer with the required options.
  83599. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  83600. */
  83601. EffectLayer.prototype._init = function (options) {
  83602. // Adapt options
  83603. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  83604. this._setMainTextureSize();
  83605. this._createMainTexture();
  83606. this._createTextureAndPostProcesses();
  83607. this._mergeEffect = this._createMergeEffect();
  83608. };
  83609. /**
  83610. * Generates the index buffer of the full screen quad blending to the main canvas.
  83611. */
  83612. EffectLayer.prototype._generateIndexBuffer = function () {
  83613. // Indices
  83614. var indices = [];
  83615. indices.push(0);
  83616. indices.push(1);
  83617. indices.push(2);
  83618. indices.push(0);
  83619. indices.push(2);
  83620. indices.push(3);
  83621. this._indexBuffer = this._engine.createIndexBuffer(indices);
  83622. };
  83623. /**
  83624. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  83625. */
  83626. EffectLayer.prototype._genrateVertexBuffer = function () {
  83627. // VBO
  83628. var vertices = [];
  83629. vertices.push(1, 1);
  83630. vertices.push(-1, 1);
  83631. vertices.push(-1, -1);
  83632. vertices.push(1, -1);
  83633. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83634. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  83635. };
  83636. /**
  83637. * Sets the main texture desired size which is the closest power of two
  83638. * of the engine canvas size.
  83639. */
  83640. EffectLayer.prototype._setMainTextureSize = function () {
  83641. if (this._effectLayerOptions.mainTextureFixedSize) {
  83642. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  83643. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  83644. }
  83645. else {
  83646. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  83647. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  83648. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  83649. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  83650. }
  83651. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  83652. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  83653. };
  83654. /**
  83655. * Creates the main texture for the effect layer.
  83656. */
  83657. EffectLayer.prototype._createMainTexture = function () {
  83658. var _this = this;
  83659. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  83660. width: this._mainTextureDesiredSize.width,
  83661. height: this._mainTextureDesiredSize.height
  83662. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83663. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  83664. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83665. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83666. this._mainTexture.anisotropicFilteringLevel = 1;
  83667. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83668. this._mainTexture.renderParticles = false;
  83669. this._mainTexture.renderList = null;
  83670. this._mainTexture.ignoreCameraViewport = true;
  83671. // Custom render function
  83672. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83673. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  83674. var index;
  83675. var engine = _this._scene.getEngine();
  83676. if (depthOnlySubMeshes.length) {
  83677. engine.setColorWrite(false);
  83678. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83679. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  83680. }
  83681. engine.setColorWrite(true);
  83682. }
  83683. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83684. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  83685. }
  83686. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83687. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  83688. }
  83689. for (index = 0; index < transparentSubMeshes.length; index++) {
  83690. _this._renderSubMesh(transparentSubMeshes.data[index]);
  83691. }
  83692. };
  83693. this._mainTexture.onClearObservable.add(function (engine) {
  83694. engine.clear(_this.neutralColor, true, true, true);
  83695. });
  83696. };
  83697. /**
  83698. * Checks for the readiness of the element composing the layer.
  83699. * @param subMesh the mesh to check for
  83700. * @param useInstances specify wether or not to use instances to render the mesh
  83701. * @param emissiveTexture the associated emissive texture used to generate the glow
  83702. * @return true if ready otherwise, false
  83703. */
  83704. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  83705. var material = subMesh.getMaterial();
  83706. if (!material) {
  83707. return false;
  83708. }
  83709. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  83710. return false;
  83711. }
  83712. var defines = [];
  83713. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83714. var mesh = subMesh.getMesh();
  83715. var uv1 = false;
  83716. var uv2 = false;
  83717. // Alpha test
  83718. if (material && material.needAlphaTesting()) {
  83719. var alphaTexture = material.getAlphaTestTexture();
  83720. if (alphaTexture) {
  83721. defines.push("#define ALPHATEST");
  83722. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  83723. alphaTexture.coordinatesIndex === 1) {
  83724. defines.push("#define DIFFUSEUV2");
  83725. uv2 = true;
  83726. }
  83727. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83728. defines.push("#define DIFFUSEUV1");
  83729. uv1 = true;
  83730. }
  83731. }
  83732. }
  83733. // Emissive
  83734. if (emissiveTexture) {
  83735. defines.push("#define EMISSIVE");
  83736. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  83737. emissiveTexture.coordinatesIndex === 1) {
  83738. defines.push("#define EMISSIVEUV2");
  83739. uv2 = true;
  83740. }
  83741. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83742. defines.push("#define EMISSIVEUV1");
  83743. uv1 = true;
  83744. }
  83745. }
  83746. if (uv1) {
  83747. attribs.push(BABYLON.VertexBuffer.UVKind);
  83748. defines.push("#define UV1");
  83749. }
  83750. if (uv2) {
  83751. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83752. defines.push("#define UV2");
  83753. }
  83754. // Bones
  83755. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83756. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83757. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83758. if (mesh.numBoneInfluencers > 4) {
  83759. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83760. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83761. }
  83762. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83763. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  83764. }
  83765. else {
  83766. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83767. }
  83768. // Instances
  83769. if (useInstances) {
  83770. defines.push("#define INSTANCES");
  83771. attribs.push("world0");
  83772. attribs.push("world1");
  83773. attribs.push("world2");
  83774. attribs.push("world3");
  83775. }
  83776. // Get correct effect
  83777. var join = defines.join("\n");
  83778. if (this._cachedDefines !== join) {
  83779. this._cachedDefines = join;
  83780. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  83781. }
  83782. return this._effectLayerMapGenerationEffect.isReady();
  83783. };
  83784. /**
  83785. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  83786. */
  83787. EffectLayer.prototype.render = function () {
  83788. var currentEffect = this._mergeEffect;
  83789. // Check
  83790. if (!currentEffect.isReady())
  83791. return;
  83792. for (var i = 0; i < this._postProcesses.length; i++) {
  83793. if (!this._postProcesses[i].isReady()) {
  83794. return;
  83795. }
  83796. }
  83797. var engine = this._scene.getEngine();
  83798. this.onBeforeComposeObservable.notifyObservers(this);
  83799. // Render
  83800. engine.enableEffect(currentEffect);
  83801. engine.setState(false);
  83802. // VBOs
  83803. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  83804. // Cache
  83805. var previousAlphaMode = engine.getAlphaMode();
  83806. // Go Blend.
  83807. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  83808. // Blends the map on the main canvas.
  83809. this._internalRender(currentEffect);
  83810. // Restore Alpha
  83811. engine.setAlphaMode(previousAlphaMode);
  83812. this.onAfterComposeObservable.notifyObservers(this);
  83813. // Handle size changes.
  83814. var size = this._mainTexture.getSize();
  83815. this._setMainTextureSize();
  83816. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  83817. // Recreate RTT and post processes on size change.
  83818. this.onSizeChangedObservable.notifyObservers(this);
  83819. this._disposeTextureAndPostProcesses();
  83820. this._createMainTexture();
  83821. this._createTextureAndPostProcesses();
  83822. }
  83823. };
  83824. /**
  83825. * Determine if a given mesh will be used in the current effect.
  83826. * @param mesh mesh to test
  83827. * @returns true if the mesh will be used
  83828. */
  83829. EffectLayer.prototype.hasMesh = function (mesh) {
  83830. return true;
  83831. };
  83832. /**
  83833. * Returns true if the layer contains information to display, otherwise false.
  83834. * @returns true if the glow layer should be rendered
  83835. */
  83836. EffectLayer.prototype.shouldRender = function () {
  83837. return this.isEnabled && this._shouldRender;
  83838. };
  83839. /**
  83840. * Returns true if the mesh should render, otherwise false.
  83841. * @param mesh The mesh to render
  83842. * @returns true if it should render otherwise false
  83843. */
  83844. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  83845. return true;
  83846. };
  83847. /**
  83848. * Returns true if the mesh should render, otherwise false.
  83849. * @param mesh The mesh to render
  83850. * @returns true if it should render otherwise false
  83851. */
  83852. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  83853. return true;
  83854. };
  83855. /**
  83856. * Renders the submesh passed in parameter to the generation map.
  83857. */
  83858. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  83859. var _this = this;
  83860. if (!this.shouldRender()) {
  83861. return;
  83862. }
  83863. var material = subMesh.getMaterial();
  83864. var mesh = subMesh.getRenderingMesh();
  83865. var scene = this._scene;
  83866. var engine = scene.getEngine();
  83867. if (!material) {
  83868. return;
  83869. }
  83870. // Do not block in blend mode.
  83871. if (material.needAlphaBlendingForMesh(mesh)) {
  83872. return;
  83873. }
  83874. // Culling
  83875. engine.setState(material.backFaceCulling);
  83876. // Managing instances
  83877. var batch = mesh._getInstancesRenderList(subMesh._id);
  83878. if (batch.mustReturn) {
  83879. return;
  83880. }
  83881. // Early Exit per mesh
  83882. if (!this._shouldRenderMesh(mesh)) {
  83883. return;
  83884. }
  83885. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83886. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  83887. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  83888. engine.enableEffect(this._effectLayerMapGenerationEffect);
  83889. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  83890. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  83891. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  83892. // Alpha test
  83893. if (material && material.needAlphaTesting()) {
  83894. var alphaTexture = material.getAlphaTestTexture();
  83895. if (alphaTexture) {
  83896. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  83897. var textureMatrix = alphaTexture.getTextureMatrix();
  83898. if (textureMatrix) {
  83899. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  83900. }
  83901. }
  83902. }
  83903. // Glow emissive only
  83904. if (this._emissiveTextureAndColor.texture) {
  83905. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  83906. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  83907. }
  83908. // Bones
  83909. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83910. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83911. }
  83912. // Draw
  83913. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  83914. }
  83915. else {
  83916. // Need to reset refresh rate of the shadowMap
  83917. this._mainTexture.resetRefreshCounter();
  83918. }
  83919. };
  83920. /**
  83921. * Rebuild the required buffers.
  83922. * @ignore Internal use only.
  83923. */
  83924. EffectLayer.prototype._rebuild = function () {
  83925. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83926. if (vb) {
  83927. vb._rebuild();
  83928. }
  83929. this._generateIndexBuffer();
  83930. };
  83931. /**
  83932. * Dispose only the render target textures and post process.
  83933. */
  83934. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  83935. this._mainTexture.dispose();
  83936. for (var i = 0; i < this._postProcesses.length; i++) {
  83937. if (this._postProcesses[i]) {
  83938. this._postProcesses[i].dispose();
  83939. }
  83940. }
  83941. this._postProcesses = [];
  83942. for (var i = 0; i < this._textures.length; i++) {
  83943. if (this._textures[i]) {
  83944. this._textures[i].dispose();
  83945. }
  83946. }
  83947. this._textures = [];
  83948. };
  83949. /**
  83950. * Dispose the highlight layer and free resources.
  83951. */
  83952. EffectLayer.prototype.dispose = function () {
  83953. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83954. if (vertexBuffer) {
  83955. vertexBuffer.dispose();
  83956. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83957. }
  83958. if (this._indexBuffer) {
  83959. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83960. this._indexBuffer = null;
  83961. }
  83962. // Clean textures and post processes
  83963. this._disposeTextureAndPostProcesses();
  83964. // Remove from scene
  83965. var index = this._scene.effectLayers.indexOf(this, 0);
  83966. if (index > -1) {
  83967. this._scene.effectLayers.splice(index, 1);
  83968. }
  83969. // Callback
  83970. this.onDisposeObservable.notifyObservers(this);
  83971. this.onDisposeObservable.clear();
  83972. this.onBeforeRenderMainTextureObservable.clear();
  83973. this.onBeforeComposeObservable.clear();
  83974. this.onAfterComposeObservable.clear();
  83975. this.onSizeChangedObservable.clear();
  83976. };
  83977. return EffectLayer;
  83978. }());
  83979. BABYLON.EffectLayer = EffectLayer;
  83980. })(BABYLON || (BABYLON = {}));
  83981. //# sourceMappingURL=babylon.effectLayer.js.map
  83982. var BABYLON;
  83983. (function (BABYLON) {
  83984. /**
  83985. * Special Glow Blur post process only blurring the alpha channel
  83986. * It enforces keeping the most luminous color in the color channel.
  83987. */
  83988. var GlowBlurPostProcess = /** @class */ (function (_super) {
  83989. __extends(GlowBlurPostProcess, _super);
  83990. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  83991. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83992. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  83993. _this.direction = direction;
  83994. _this.kernel = kernel;
  83995. _this.onApplyObservable.add(function (effect) {
  83996. effect.setFloat2("screenSize", _this.width, _this.height);
  83997. effect.setVector2("direction", _this.direction);
  83998. effect.setFloat("blurWidth", _this.kernel);
  83999. });
  84000. return _this;
  84001. }
  84002. return GlowBlurPostProcess;
  84003. }(BABYLON.PostProcess));
  84004. /**
  84005. * The highlight layer Helps adding a glow effect around a mesh.
  84006. *
  84007. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84008. * glowy meshes to your scene.
  84009. *
  84010. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  84011. */
  84012. var HighlightLayer = /** @class */ (function (_super) {
  84013. __extends(HighlightLayer, _super);
  84014. /**
  84015. * Instantiates a new highlight Layer and references it to the scene..
  84016. * @param name The name of the layer
  84017. * @param scene The scene to use the layer in
  84018. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  84019. */
  84020. function HighlightLayer(name, scene, options) {
  84021. var _this = _super.call(this, name, scene) || this;
  84022. _this.name = name;
  84023. /**
  84024. * Specifies whether or not the inner glow is ACTIVE in the layer.
  84025. */
  84026. _this.innerGlow = true;
  84027. /**
  84028. * Specifies whether or not the outer glow is ACTIVE in the layer.
  84029. */
  84030. _this.outerGlow = true;
  84031. /**
  84032. * An event triggered when the highlight layer is being blurred.
  84033. */
  84034. _this.onBeforeBlurObservable = new BABYLON.Observable();
  84035. /**
  84036. * An event triggered when the highlight layer has been blurred.
  84037. */
  84038. _this.onAfterBlurObservable = new BABYLON.Observable();
  84039. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  84040. _this._meshes = {};
  84041. _this._excludedMeshes = {};
  84042. _this.neutralColor = HighlightLayer.NeutralColor;
  84043. // Warn on stencil
  84044. if (!_this._engine.isStencilEnable) {
  84045. 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 }");
  84046. }
  84047. // Adapt options
  84048. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84049. // Initialize the layer
  84050. _this._init({
  84051. alphaBlendingMode: _this._options.alphaBlendingMode,
  84052. camera: _this._options.camera,
  84053. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84054. mainTextureRatio: _this._options.mainTextureRatio
  84055. });
  84056. // Do not render as long as no meshes have been added
  84057. _this._shouldRender = false;
  84058. return _this;
  84059. }
  84060. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  84061. /**
  84062. * Gets the horizontal size of the blur.
  84063. */
  84064. get: function () {
  84065. return this._horizontalBlurPostprocess.kernel;
  84066. },
  84067. /**
  84068. * Specifies the horizontal size of the blur.
  84069. */
  84070. set: function (value) {
  84071. this._horizontalBlurPostprocess.kernel = value;
  84072. },
  84073. enumerable: true,
  84074. configurable: true
  84075. });
  84076. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  84077. /**
  84078. * Gets the vertical size of the blur.
  84079. */
  84080. get: function () {
  84081. return this._verticalBlurPostprocess.kernel;
  84082. },
  84083. /**
  84084. * Specifies the vertical size of the blur.
  84085. */
  84086. set: function (value) {
  84087. this._verticalBlurPostprocess.kernel = value;
  84088. },
  84089. enumerable: true,
  84090. configurable: true
  84091. });
  84092. /**
  84093. * Get the effect name of the layer.
  84094. * @return The effect name
  84095. */
  84096. HighlightLayer.prototype.getEffectName = function () {
  84097. return HighlightLayer.EffectName;
  84098. };
  84099. /**
  84100. * Create the merge effect. This is the shader use to blit the information back
  84101. * to the main canvas at the end of the scene rendering.
  84102. */
  84103. HighlightLayer.prototype._createMergeEffect = function () {
  84104. // Effect
  84105. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  84106. };
  84107. /**
  84108. * Creates the render target textures and post processes used in the highlight layer.
  84109. */
  84110. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  84111. var _this = this;
  84112. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  84113. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  84114. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84115. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84116. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  84117. width: blurTextureWidth,
  84118. height: blurTextureHeight
  84119. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84120. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84121. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84122. this._blurTexture.anisotropicFilteringLevel = 16;
  84123. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84124. this._blurTexture.renderParticles = false;
  84125. this._blurTexture.ignoreCameraViewport = true;
  84126. this._textures = [this._blurTexture];
  84127. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  84128. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84129. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  84130. effect.setTexture("textureSampler", _this._mainTexture);
  84131. });
  84132. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84133. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84134. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84135. });
  84136. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84137. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  84138. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84139. });
  84140. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84141. }
  84142. else {
  84143. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  84144. width: blurTextureWidth,
  84145. height: blurTextureHeight
  84146. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84147. this._horizontalBlurPostprocess.width = blurTextureWidth;
  84148. this._horizontalBlurPostprocess.height = blurTextureHeight;
  84149. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84150. effect.setTexture("textureSampler", _this._mainTexture);
  84151. });
  84152. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  84153. width: blurTextureWidth,
  84154. height: blurTextureHeight
  84155. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84156. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84157. }
  84158. this._mainTexture.onAfterUnbindObservable.add(function () {
  84159. _this.onBeforeBlurObservable.notifyObservers(_this);
  84160. var internalTexture = _this._blurTexture.getInternalTexture();
  84161. if (internalTexture) {
  84162. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  84163. }
  84164. _this.onAfterBlurObservable.notifyObservers(_this);
  84165. });
  84166. // Prevent autoClear.
  84167. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84168. };
  84169. /**
  84170. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84171. */
  84172. HighlightLayer.prototype.needStencil = function () {
  84173. return true;
  84174. };
  84175. /**
  84176. * Checks for the readiness of the element composing the layer.
  84177. * @param subMesh the mesh to check for
  84178. * @param useInstances specify wether or not to use instances to render the mesh
  84179. * @param emissiveTexture the associated emissive texture used to generate the glow
  84180. * @return true if ready otherwise, false
  84181. */
  84182. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  84183. var material = subMesh.getMaterial();
  84184. var mesh = subMesh.getRenderingMesh();
  84185. if (!material || !mesh || !this._meshes) {
  84186. return false;
  84187. }
  84188. var emissiveTexture = null;
  84189. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84190. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84191. emissiveTexture = material.emissiveTexture;
  84192. }
  84193. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84194. };
  84195. /**
  84196. * Implementation specific of rendering the generating effect on the main canvas.
  84197. * @param effect The effect used to render through
  84198. */
  84199. HighlightLayer.prototype._internalRender = function (effect) {
  84200. // Texture
  84201. effect.setTexture("textureSampler", this._blurTexture);
  84202. // Cache
  84203. var engine = this._engine;
  84204. var previousStencilBuffer = engine.getStencilBuffer();
  84205. var previousStencilFunction = engine.getStencilFunction();
  84206. var previousStencilMask = engine.getStencilMask();
  84207. var previousStencilOperationPass = engine.getStencilOperationPass();
  84208. var previousStencilOperationFail = engine.getStencilOperationFail();
  84209. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  84210. var previousStencilReference = engine.getStencilFunctionReference();
  84211. // Stencil operations
  84212. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  84213. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  84214. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  84215. // Draw order
  84216. engine.setStencilMask(0x00);
  84217. engine.setStencilBuffer(true);
  84218. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  84219. // 2 passes inner outer
  84220. if (this.outerGlow) {
  84221. effect.setFloat("offset", 0);
  84222. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  84223. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84224. }
  84225. if (this.innerGlow) {
  84226. effect.setFloat("offset", 1);
  84227. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  84228. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84229. }
  84230. // Restore Cache
  84231. engine.setStencilFunction(previousStencilFunction);
  84232. engine.setStencilMask(previousStencilMask);
  84233. engine.setStencilBuffer(previousStencilBuffer);
  84234. engine.setStencilOperationPass(previousStencilOperationPass);
  84235. engine.setStencilOperationFail(previousStencilOperationFail);
  84236. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  84237. engine.setStencilFunctionReference(previousStencilReference);
  84238. };
  84239. /**
  84240. * Returns true if the layer contains information to display, otherwise false.
  84241. */
  84242. HighlightLayer.prototype.shouldRender = function () {
  84243. if (_super.prototype.shouldRender.call(this)) {
  84244. return this._meshes ? true : false;
  84245. }
  84246. return false;
  84247. };
  84248. /**
  84249. * Returns true if the mesh should render, otherwise false.
  84250. * @param mesh The mesh to render
  84251. * @returns true if it should render otherwise false
  84252. */
  84253. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  84254. // Excluded Mesh
  84255. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  84256. return false;
  84257. }
  84258. ;
  84259. return true;
  84260. };
  84261. /**
  84262. * Sets the required values for both the emissive texture and and the main color.
  84263. */
  84264. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84265. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84266. if (highlightLayerMesh) {
  84267. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  84268. }
  84269. else {
  84270. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84271. }
  84272. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84273. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84274. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  84275. }
  84276. else {
  84277. this._emissiveTextureAndColor.texture = null;
  84278. }
  84279. };
  84280. /**
  84281. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  84282. * @param mesh The mesh to exclude from the highlight layer
  84283. */
  84284. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  84285. if (!this._excludedMeshes) {
  84286. return;
  84287. }
  84288. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84289. if (!meshExcluded) {
  84290. this._excludedMeshes[mesh.uniqueId] = {
  84291. mesh: mesh,
  84292. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  84293. mesh.getEngine().setStencilBuffer(false);
  84294. }),
  84295. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  84296. mesh.getEngine().setStencilBuffer(true);
  84297. }),
  84298. };
  84299. }
  84300. };
  84301. /**
  84302. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  84303. * @param mesh The mesh to highlight
  84304. */
  84305. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  84306. if (!this._excludedMeshes) {
  84307. return;
  84308. }
  84309. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84310. if (meshExcluded) {
  84311. if (meshExcluded.beforeRender) {
  84312. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  84313. }
  84314. if (meshExcluded.afterRender) {
  84315. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  84316. }
  84317. }
  84318. this._excludedMeshes[mesh.uniqueId] = null;
  84319. };
  84320. /**
  84321. * Determine if a given mesh will be highlighted by the current HighlightLayer
  84322. * @param mesh mesh to test
  84323. * @returns true if the mesh will be highlighted by the current HighlightLayer
  84324. */
  84325. HighlightLayer.prototype.hasMesh = function (mesh) {
  84326. if (!this._meshes) {
  84327. return false;
  84328. }
  84329. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  84330. };
  84331. /**
  84332. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  84333. * @param mesh The mesh to highlight
  84334. * @param color The color of the highlight
  84335. * @param glowEmissiveOnly Extract the glow from the emissive texture
  84336. */
  84337. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  84338. var _this = this;
  84339. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  84340. if (!this._meshes) {
  84341. return;
  84342. }
  84343. var meshHighlight = this._meshes[mesh.uniqueId];
  84344. if (meshHighlight) {
  84345. meshHighlight.color = color;
  84346. }
  84347. else {
  84348. this._meshes[mesh.uniqueId] = {
  84349. mesh: mesh,
  84350. color: color,
  84351. // Lambda required for capture due to Observable this context
  84352. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  84353. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  84354. _this._defaultStencilReference(mesh);
  84355. }
  84356. else {
  84357. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  84358. }
  84359. }),
  84360. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  84361. glowEmissiveOnly: glowEmissiveOnly
  84362. };
  84363. }
  84364. this._shouldRender = true;
  84365. };
  84366. /**
  84367. * Remove a mesh from the highlight layer in order to make it stop glowing.
  84368. * @param mesh The mesh to highlight
  84369. */
  84370. HighlightLayer.prototype.removeMesh = function (mesh) {
  84371. if (!this._meshes) {
  84372. return;
  84373. }
  84374. var meshHighlight = this._meshes[mesh.uniqueId];
  84375. if (meshHighlight) {
  84376. if (meshHighlight.observerHighlight) {
  84377. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84378. }
  84379. if (meshHighlight.observerDefault) {
  84380. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84381. }
  84382. delete this._meshes[mesh.uniqueId];
  84383. }
  84384. this._shouldRender = false;
  84385. for (var meshHighlightToCheck in this._meshes) {
  84386. if (this._meshes[meshHighlightToCheck]) {
  84387. this._shouldRender = true;
  84388. break;
  84389. }
  84390. }
  84391. };
  84392. /**
  84393. * Force the stencil to the normal expected value for none glowing parts
  84394. */
  84395. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  84396. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  84397. };
  84398. /**
  84399. * Free any resources and references associated to a mesh.
  84400. * Internal use
  84401. * @param mesh The mesh to free.
  84402. */
  84403. HighlightLayer.prototype._disposeMesh = function (mesh) {
  84404. this.removeMesh(mesh);
  84405. this.removeExcludedMesh(mesh);
  84406. };
  84407. /**
  84408. * Dispose the highlight layer and free resources.
  84409. */
  84410. HighlightLayer.prototype.dispose = function () {
  84411. if (this._meshes) {
  84412. // Clean mesh references
  84413. for (var id in this._meshes) {
  84414. var meshHighlight = this._meshes[id];
  84415. if (meshHighlight && meshHighlight.mesh) {
  84416. if (meshHighlight.observerHighlight) {
  84417. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84418. }
  84419. if (meshHighlight.observerDefault) {
  84420. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84421. }
  84422. }
  84423. }
  84424. this._meshes = null;
  84425. }
  84426. if (this._excludedMeshes) {
  84427. for (var id in this._excludedMeshes) {
  84428. var meshHighlight = this._excludedMeshes[id];
  84429. if (meshHighlight) {
  84430. if (meshHighlight.beforeRender) {
  84431. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  84432. }
  84433. if (meshHighlight.afterRender) {
  84434. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  84435. }
  84436. }
  84437. }
  84438. this._excludedMeshes = null;
  84439. }
  84440. _super.prototype.dispose.call(this);
  84441. };
  84442. /**
  84443. * Effect Name of the highlight layer.
  84444. */
  84445. HighlightLayer.EffectName = "HighlightLayer";
  84446. /**
  84447. * The neutral color used during the preparation of the glow effect.
  84448. * This is black by default as the blend operation is a blend operation.
  84449. */
  84450. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  84451. /**
  84452. * Stencil value used for glowing meshes.
  84453. */
  84454. HighlightLayer.GlowingMeshStencilReference = 0x02;
  84455. /**
  84456. * Stencil value used for the other meshes in the scene.
  84457. */
  84458. HighlightLayer.NormalMeshStencilReference = 0x01;
  84459. return HighlightLayer;
  84460. }(BABYLON.EffectLayer));
  84461. BABYLON.HighlightLayer = HighlightLayer;
  84462. })(BABYLON || (BABYLON = {}));
  84463. //# sourceMappingURL=babylon.highlightLayer.js.map
  84464. var BABYLON;
  84465. (function (BABYLON) {
  84466. /**
  84467. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  84468. *
  84469. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84470. * glowy meshes to your scene.
  84471. *
  84472. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  84473. */
  84474. var GlowLayer = /** @class */ (function (_super) {
  84475. __extends(GlowLayer, _super);
  84476. /**
  84477. * Instantiates a new glow Layer and references it to the scene.
  84478. * @param name The name of the layer
  84479. * @param scene The scene to use the layer in
  84480. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  84481. */
  84482. function GlowLayer(name, scene, options) {
  84483. var _this = _super.call(this, name, scene) || this;
  84484. _this.name = name;
  84485. _this._intensity = 1.0;
  84486. _this._includedOnlyMeshes = [];
  84487. _this._excludedMeshes = [];
  84488. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  84489. // Adapt options
  84490. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  84491. // Initialize the layer
  84492. _this._init({
  84493. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  84494. camera: _this._options.camera,
  84495. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84496. mainTextureRatio: _this._options.mainTextureRatio
  84497. });
  84498. return _this;
  84499. }
  84500. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  84501. /**
  84502. * Gets the kernel size of the blur.
  84503. */
  84504. get: function () {
  84505. return this._horizontalBlurPostprocess1.kernel;
  84506. },
  84507. /**
  84508. * Sets the kernel size of the blur.
  84509. */
  84510. set: function (value) {
  84511. this._horizontalBlurPostprocess1.kernel = value;
  84512. this._verticalBlurPostprocess1.kernel = value;
  84513. this._horizontalBlurPostprocess2.kernel = value;
  84514. this._verticalBlurPostprocess2.kernel = value;
  84515. },
  84516. enumerable: true,
  84517. configurable: true
  84518. });
  84519. Object.defineProperty(GlowLayer.prototype, "intensity", {
  84520. /**
  84521. * Gets the glow intensity.
  84522. */
  84523. get: function () {
  84524. return this._intensity;
  84525. },
  84526. /**
  84527. * Sets the glow intensity.
  84528. */
  84529. set: function (value) {
  84530. this._intensity = value;
  84531. },
  84532. enumerable: true,
  84533. configurable: true
  84534. });
  84535. /**
  84536. * Get the effect name of the layer.
  84537. * @return The effect name
  84538. */
  84539. GlowLayer.prototype.getEffectName = function () {
  84540. return GlowLayer.EffectName;
  84541. };
  84542. /**
  84543. * Create the merge effect. This is the shader use to blit the information back
  84544. * to the main canvas at the end of the scene rendering.
  84545. */
  84546. GlowLayer.prototype._createMergeEffect = function () {
  84547. // Effect
  84548. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  84549. };
  84550. /**
  84551. * Creates the render target textures and post processes used in the glow layer.
  84552. */
  84553. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  84554. var _this = this;
  84555. var blurTextureWidth = this._mainTextureDesiredSize.width;
  84556. var blurTextureHeight = this._mainTextureDesiredSize.height;
  84557. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84558. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84559. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  84560. width: blurTextureWidth,
  84561. height: blurTextureHeight
  84562. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84563. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84564. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84565. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84566. this._blurTexture1.renderParticles = false;
  84567. this._blurTexture1.ignoreCameraViewport = true;
  84568. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  84569. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  84570. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  84571. width: blurTextureWidth2,
  84572. height: blurTextureHeight2
  84573. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84574. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84575. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84576. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84577. this._blurTexture2.renderParticles = false;
  84578. this._blurTexture2.ignoreCameraViewport = true;
  84579. this._textures = [this._blurTexture1, this._blurTexture2];
  84580. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84581. width: blurTextureWidth,
  84582. height: blurTextureHeight
  84583. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84584. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  84585. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  84586. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  84587. effect.setTexture("textureSampler", _this._mainTexture);
  84588. });
  84589. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84590. width: blurTextureWidth,
  84591. height: blurTextureHeight
  84592. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84593. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84594. width: blurTextureWidth2,
  84595. height: blurTextureHeight2
  84596. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84597. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  84598. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  84599. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  84600. effect.setTexture("textureSampler", _this._blurTexture1);
  84601. });
  84602. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84603. width: blurTextureWidth2,
  84604. height: blurTextureHeight2
  84605. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84606. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84607. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  84608. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84609. this._mainTexture.samples = this._options.mainTextureSamples;
  84610. this._mainTexture.onAfterUnbindObservable.add(function () {
  84611. var internalTexture = _this._blurTexture1.getInternalTexture();
  84612. if (internalTexture) {
  84613. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  84614. internalTexture = _this._blurTexture2.getInternalTexture();
  84615. if (internalTexture) {
  84616. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  84617. }
  84618. }
  84619. });
  84620. // Prevent autoClear.
  84621. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84622. };
  84623. /**
  84624. * Checks for the readiness of the element composing the layer.
  84625. * @param subMesh the mesh to check for
  84626. * @param useInstances specify wether or not to use instances to render the mesh
  84627. * @param emissiveTexture the associated emissive texture used to generate the glow
  84628. * @return true if ready otherwise, false
  84629. */
  84630. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  84631. var material = subMesh.getMaterial();
  84632. var mesh = subMesh.getRenderingMesh();
  84633. if (!material || !mesh) {
  84634. return false;
  84635. }
  84636. var emissiveTexture = material.emissiveTexture;
  84637. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84638. };
  84639. /**
  84640. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84641. */
  84642. GlowLayer.prototype.needStencil = function () {
  84643. return false;
  84644. };
  84645. /**
  84646. * Implementation specific of rendering the generating effect on the main canvas.
  84647. * @param effect The effect used to render through
  84648. */
  84649. GlowLayer.prototype._internalRender = function (effect) {
  84650. // Texture
  84651. effect.setTexture("textureSampler", this._blurTexture1);
  84652. effect.setTexture("textureSampler2", this._blurTexture2);
  84653. effect.setFloat("offset", this._intensity);
  84654. // Cache
  84655. var engine = this._engine;
  84656. var previousStencilBuffer = engine.getStencilBuffer();
  84657. // Draw order
  84658. engine.setStencilBuffer(false);
  84659. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84660. // Draw order
  84661. engine.setStencilBuffer(previousStencilBuffer);
  84662. };
  84663. /**
  84664. * Sets the required values for both the emissive texture and and the main color.
  84665. */
  84666. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84667. var textureLevel = 1.0;
  84668. if (this.customEmissiveTextureSelector) {
  84669. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  84670. }
  84671. else {
  84672. if (material) {
  84673. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84674. if (this._emissiveTextureAndColor.texture) {
  84675. textureLevel = this._emissiveTextureAndColor.texture.level;
  84676. }
  84677. }
  84678. else {
  84679. this._emissiveTextureAndColor.texture = null;
  84680. }
  84681. }
  84682. if (this.customEmissiveColorSelector) {
  84683. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  84684. }
  84685. else {
  84686. if (material.emissiveColor) {
  84687. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  84688. }
  84689. else {
  84690. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84691. }
  84692. }
  84693. };
  84694. /**
  84695. * Returns true if the mesh should render, otherwise false.
  84696. * @param mesh The mesh to render
  84697. * @returns true if it should render otherwise false
  84698. */
  84699. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  84700. return this.hasMesh(mesh);
  84701. };
  84702. /**
  84703. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  84704. * @param mesh The mesh to exclude from the glow layer
  84705. */
  84706. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  84707. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  84708. this._excludedMeshes.push(mesh.uniqueId);
  84709. }
  84710. };
  84711. /**
  84712. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  84713. * @param mesh The mesh to remove
  84714. */
  84715. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  84716. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  84717. if (index !== -1) {
  84718. this._excludedMeshes.splice(index, 1);
  84719. }
  84720. };
  84721. /**
  84722. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  84723. * @param mesh The mesh to include in the glow layer
  84724. */
  84725. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  84726. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  84727. this._includedOnlyMeshes.push(mesh.uniqueId);
  84728. }
  84729. };
  84730. /**
  84731. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  84732. * @param mesh The mesh to remove
  84733. */
  84734. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  84735. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  84736. if (index !== -1) {
  84737. this._includedOnlyMeshes.splice(index, 1);
  84738. }
  84739. };
  84740. /**
  84741. * Determine if a given mesh will be used in the glow layer
  84742. * @param mesh The mesh to test
  84743. * @returns true if the mesh will be highlighted by the current glow layer
  84744. */
  84745. GlowLayer.prototype.hasMesh = function (mesh) {
  84746. // Included Mesh
  84747. if (this._includedOnlyMeshes.length) {
  84748. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  84749. }
  84750. ;
  84751. // Excluded Mesh
  84752. if (this._excludedMeshes.length) {
  84753. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  84754. }
  84755. ;
  84756. return true;
  84757. };
  84758. /**
  84759. * Free any resources and references associated to a mesh.
  84760. * Internal use
  84761. * @param mesh The mesh to free.
  84762. */
  84763. GlowLayer.prototype._disposeMesh = function (mesh) {
  84764. this.removeIncludedOnlyMesh(mesh);
  84765. this.removeExcludedMesh(mesh);
  84766. };
  84767. /**
  84768. * Effect Name of the layer.
  84769. */
  84770. GlowLayer.EffectName = "GlowLayer";
  84771. /**
  84772. * The default blur kernel size used for the glow.
  84773. */
  84774. GlowLayer.DefaultBlurKernelSize = 32;
  84775. /**
  84776. * The default texture size ratio used for the glow.
  84777. */
  84778. GlowLayer.DefaultTextureRatio = 0.5;
  84779. return GlowLayer;
  84780. }(BABYLON.EffectLayer));
  84781. BABYLON.GlowLayer = GlowLayer;
  84782. })(BABYLON || (BABYLON = {}));
  84783. //# sourceMappingURL=babylon.glowLayer.js.map
  84784. var BABYLON;
  84785. (function (BABYLON) {
  84786. /**
  84787. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  84788. */
  84789. var AssetTaskState;
  84790. (function (AssetTaskState) {
  84791. /**
  84792. * Initialization
  84793. */
  84794. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  84795. /**
  84796. * Running
  84797. */
  84798. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  84799. /**
  84800. * Done
  84801. */
  84802. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  84803. /**
  84804. * Error
  84805. */
  84806. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  84807. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  84808. /**
  84809. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  84810. */
  84811. var AbstractAssetTask = /** @class */ (function () {
  84812. /**
  84813. * Creates a new {BABYLON.AssetsManager}
  84814. * @param name defines the name of the task
  84815. */
  84816. function AbstractAssetTask(
  84817. /**
  84818. * Task name
  84819. */ name) {
  84820. this.name = name;
  84821. this._isCompleted = false;
  84822. this._taskState = AssetTaskState.INIT;
  84823. }
  84824. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  84825. /**
  84826. * Get if the task is completed
  84827. */
  84828. get: function () {
  84829. return this._isCompleted;
  84830. },
  84831. enumerable: true,
  84832. configurable: true
  84833. });
  84834. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  84835. /**
  84836. * Gets the current state of the task
  84837. */
  84838. get: function () {
  84839. return this._taskState;
  84840. },
  84841. enumerable: true,
  84842. configurable: true
  84843. });
  84844. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  84845. /**
  84846. * Gets the current error object (if task is in error)
  84847. */
  84848. get: function () {
  84849. return this._errorObject;
  84850. },
  84851. enumerable: true,
  84852. configurable: true
  84853. });
  84854. /**
  84855. * Internal only
  84856. * @ignore
  84857. */
  84858. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  84859. if (this._errorObject) {
  84860. return;
  84861. }
  84862. this._errorObject = {
  84863. message: message,
  84864. exception: exception
  84865. };
  84866. };
  84867. /**
  84868. * Execute the current task
  84869. * @param scene defines the scene where you want your assets to be loaded
  84870. * @param onSuccess is a callback called when the task is successfully executed
  84871. * @param onError is a callback called if an error occurs
  84872. */
  84873. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  84874. var _this = this;
  84875. this._taskState = AssetTaskState.RUNNING;
  84876. this.runTask(scene, function () {
  84877. _this.onDoneCallback(onSuccess, onError);
  84878. }, function (msg, exception) {
  84879. _this.onErrorCallback(onError, msg, exception);
  84880. });
  84881. };
  84882. /**
  84883. * Execute the current task
  84884. * @param scene defines the scene where you want your assets to be loaded
  84885. * @param onSuccess is a callback called when the task is successfully executed
  84886. * @param onError is a callback called if an error occurs
  84887. */
  84888. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84889. throw new Error("runTask is not implemented");
  84890. };
  84891. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  84892. this._taskState = AssetTaskState.ERROR;
  84893. this._errorObject = {
  84894. message: message,
  84895. exception: exception
  84896. };
  84897. if (this.onError) {
  84898. this.onError(this, message, exception);
  84899. }
  84900. onError();
  84901. };
  84902. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  84903. try {
  84904. this._taskState = AssetTaskState.DONE;
  84905. this._isCompleted = true;
  84906. if (this.onSuccess) {
  84907. this.onSuccess(this);
  84908. }
  84909. onSuccess();
  84910. }
  84911. catch (e) {
  84912. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  84913. }
  84914. };
  84915. return AbstractAssetTask;
  84916. }());
  84917. BABYLON.AbstractAssetTask = AbstractAssetTask;
  84918. /**
  84919. * Class used to share progress information about assets loading
  84920. */
  84921. var AssetsProgressEvent = /** @class */ (function () {
  84922. /**
  84923. * Creates a {BABYLON.AssetsProgressEvent}
  84924. * @param remainingCount defines the number of remaining tasks to process
  84925. * @param totalCount defines the total number of tasks
  84926. * @param task defines the task that was just processed
  84927. */
  84928. function AssetsProgressEvent(remainingCount, totalCount, task) {
  84929. this.remainingCount = remainingCount;
  84930. this.totalCount = totalCount;
  84931. this.task = task;
  84932. }
  84933. return AssetsProgressEvent;
  84934. }());
  84935. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  84936. /**
  84937. * Define a task used by {BABYLON.AssetsManager} to load meshes
  84938. */
  84939. var MeshAssetTask = /** @class */ (function (_super) {
  84940. __extends(MeshAssetTask, _super);
  84941. /**
  84942. * Creates a new {BABYLON.MeshAssetTask}
  84943. * @param name defines the name of the task
  84944. * @param meshesNames defines the list of mesh's names you want to load
  84945. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  84946. * @param sceneFilename defines the filename of the scene to load from
  84947. */
  84948. function MeshAssetTask(
  84949. /**
  84950. * Defines the name of the task
  84951. */
  84952. name,
  84953. /**
  84954. * Defines the list of mesh's names you want to load
  84955. */
  84956. meshesNames,
  84957. /**
  84958. * Defines the root url to use as a base to load your meshes and associated resources
  84959. */
  84960. rootUrl,
  84961. /**
  84962. * Defines the filename of the scene to load from
  84963. */
  84964. sceneFilename) {
  84965. var _this = _super.call(this, name) || this;
  84966. _this.name = name;
  84967. _this.meshesNames = meshesNames;
  84968. _this.rootUrl = rootUrl;
  84969. _this.sceneFilename = sceneFilename;
  84970. return _this;
  84971. }
  84972. /**
  84973. * Execute the current task
  84974. * @param scene defines the scene where you want your assets to be loaded
  84975. * @param onSuccess is a callback called when the task is successfully executed
  84976. * @param onError is a callback called if an error occurs
  84977. */
  84978. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84979. var _this = this;
  84980. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  84981. _this.loadedMeshes = meshes;
  84982. _this.loadedParticleSystems = particleSystems;
  84983. _this.loadedSkeletons = skeletons;
  84984. onSuccess();
  84985. }, null, function (scene, message, exception) {
  84986. onError(message, exception);
  84987. });
  84988. };
  84989. return MeshAssetTask;
  84990. }(AbstractAssetTask));
  84991. BABYLON.MeshAssetTask = MeshAssetTask;
  84992. /**
  84993. * Define a task used by {BABYLON.AssetsManager} to load text content
  84994. */
  84995. var TextFileAssetTask = /** @class */ (function (_super) {
  84996. __extends(TextFileAssetTask, _super);
  84997. /**
  84998. * Creates a new TextFileAssetTask object
  84999. * @param name defines the name of the task
  85000. * @param url defines the location of the file to load
  85001. */
  85002. function TextFileAssetTask(
  85003. /**
  85004. * Defines the name of the task
  85005. */
  85006. name,
  85007. /**
  85008. * Defines the location of the file to load
  85009. */
  85010. url) {
  85011. var _this = _super.call(this, name) || this;
  85012. _this.name = name;
  85013. _this.url = url;
  85014. return _this;
  85015. }
  85016. /**
  85017. * Execute the current task
  85018. * @param scene defines the scene where you want your assets to be loaded
  85019. * @param onSuccess is a callback called when the task is successfully executed
  85020. * @param onError is a callback called if an error occurs
  85021. */
  85022. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85023. var _this = this;
  85024. scene._loadFile(this.url, function (data) {
  85025. _this.text = data;
  85026. onSuccess();
  85027. }, undefined, false, false, function (request, exception) {
  85028. if (request) {
  85029. onError(request.status + " " + request.statusText, exception);
  85030. }
  85031. });
  85032. };
  85033. return TextFileAssetTask;
  85034. }(AbstractAssetTask));
  85035. BABYLON.TextFileAssetTask = TextFileAssetTask;
  85036. /**
  85037. * Define a task used by {BABYLON.AssetsManager} to load binary data
  85038. */
  85039. var BinaryFileAssetTask = /** @class */ (function (_super) {
  85040. __extends(BinaryFileAssetTask, _super);
  85041. /**
  85042. * Creates a new BinaryFileAssetTask object
  85043. * @param name defines the name of the new task
  85044. * @param url defines the location of the file to load
  85045. */
  85046. function BinaryFileAssetTask(
  85047. /**
  85048. * Defines the name of the task
  85049. */
  85050. name,
  85051. /**
  85052. * Defines the location of the file to load
  85053. */
  85054. url) {
  85055. var _this = _super.call(this, name) || this;
  85056. _this.name = name;
  85057. _this.url = url;
  85058. return _this;
  85059. }
  85060. /**
  85061. * Execute the current task
  85062. * @param scene defines the scene where you want your assets to be loaded
  85063. * @param onSuccess is a callback called when the task is successfully executed
  85064. * @param onError is a callback called if an error occurs
  85065. */
  85066. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85067. var _this = this;
  85068. scene._loadFile(this.url, function (data) {
  85069. _this.data = data;
  85070. onSuccess();
  85071. }, undefined, true, true, function (request, exception) {
  85072. if (request) {
  85073. onError(request.status + " " + request.statusText, exception);
  85074. }
  85075. });
  85076. };
  85077. return BinaryFileAssetTask;
  85078. }(AbstractAssetTask));
  85079. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  85080. /**
  85081. * Define a task used by {BABYLON.AssetsManager} to load images
  85082. */
  85083. var ImageAssetTask = /** @class */ (function (_super) {
  85084. __extends(ImageAssetTask, _super);
  85085. /**
  85086. * Creates a new ImageAssetTask
  85087. * @param name defines the name of the task
  85088. * @param url defines the location of the image to load
  85089. */
  85090. function ImageAssetTask(
  85091. /**
  85092. * Defines the name of the task
  85093. */
  85094. name,
  85095. /**
  85096. * Defines the location of the image to load
  85097. */
  85098. url) {
  85099. var _this = _super.call(this, name) || this;
  85100. _this.name = name;
  85101. _this.url = url;
  85102. return _this;
  85103. }
  85104. /**
  85105. * Execute the current task
  85106. * @param scene defines the scene where you want your assets to be loaded
  85107. * @param onSuccess is a callback called when the task is successfully executed
  85108. * @param onError is a callback called if an error occurs
  85109. */
  85110. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85111. var _this = this;
  85112. var img = new Image();
  85113. BABYLON.Tools.SetCorsBehavior(this.url, img);
  85114. img.onload = function () {
  85115. _this.image = img;
  85116. onSuccess();
  85117. };
  85118. img.onerror = function (err) {
  85119. onError("Error loading image", err);
  85120. };
  85121. img.src = this.url;
  85122. };
  85123. return ImageAssetTask;
  85124. }(AbstractAssetTask));
  85125. BABYLON.ImageAssetTask = ImageAssetTask;
  85126. /**
  85127. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  85128. */
  85129. var TextureAssetTask = /** @class */ (function (_super) {
  85130. __extends(TextureAssetTask, _super);
  85131. /**
  85132. * Creates a new TextureAssetTask object
  85133. * @param name defines the name of the task
  85134. * @param url defines the location of the file to load
  85135. * @param noMipmap defines if mipmap should not be generated (default is false)
  85136. * @param invertY defines if texture must be inverted on Y axis (default is false)
  85137. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85138. */
  85139. function TextureAssetTask(
  85140. /**
  85141. * Defines the name of the task
  85142. */
  85143. name,
  85144. /**
  85145. * Defines the location of the file to load
  85146. */
  85147. url,
  85148. /**
  85149. * Defines if mipmap should not be generated (default is false)
  85150. */
  85151. noMipmap,
  85152. /**
  85153. * Defines if texture must be inverted on Y axis (default is false)
  85154. */
  85155. invertY,
  85156. /**
  85157. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85158. */
  85159. samplingMode) {
  85160. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85161. var _this = _super.call(this, name) || this;
  85162. _this.name = name;
  85163. _this.url = url;
  85164. _this.noMipmap = noMipmap;
  85165. _this.invertY = invertY;
  85166. _this.samplingMode = samplingMode;
  85167. return _this;
  85168. }
  85169. /**
  85170. * Execute the current task
  85171. * @param scene defines the scene where you want your assets to be loaded
  85172. * @param onSuccess is a callback called when the task is successfully executed
  85173. * @param onError is a callback called if an error occurs
  85174. */
  85175. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85176. var onload = function () {
  85177. onSuccess();
  85178. };
  85179. var onerror = function (message, exception) {
  85180. onError(message, exception);
  85181. };
  85182. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  85183. };
  85184. return TextureAssetTask;
  85185. }(AbstractAssetTask));
  85186. BABYLON.TextureAssetTask = TextureAssetTask;
  85187. /**
  85188. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  85189. */
  85190. var CubeTextureAssetTask = /** @class */ (function (_super) {
  85191. __extends(CubeTextureAssetTask, _super);
  85192. /**
  85193. * Creates a new CubeTextureAssetTask
  85194. * @param name defines the name of the task
  85195. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85196. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85197. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85198. * @param files defines the explicit list of files (undefined by default)
  85199. */
  85200. function CubeTextureAssetTask(
  85201. /**
  85202. * Defines the name of the task
  85203. */
  85204. name,
  85205. /**
  85206. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85207. */
  85208. url,
  85209. /**
  85210. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85211. */
  85212. extensions,
  85213. /**
  85214. * Defines if mipmaps should not be generated (default is false)
  85215. */
  85216. noMipmap,
  85217. /**
  85218. * Defines the explicit list of files (undefined by default)
  85219. */
  85220. files) {
  85221. var _this = _super.call(this, name) || this;
  85222. _this.name = name;
  85223. _this.url = url;
  85224. _this.extensions = extensions;
  85225. _this.noMipmap = noMipmap;
  85226. _this.files = files;
  85227. return _this;
  85228. }
  85229. /**
  85230. * Execute the current task
  85231. * @param scene defines the scene where you want your assets to be loaded
  85232. * @param onSuccess is a callback called when the task is successfully executed
  85233. * @param onError is a callback called if an error occurs
  85234. */
  85235. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85236. var onload = function () {
  85237. onSuccess();
  85238. };
  85239. var onerror = function (message, exception) {
  85240. onError(message, exception);
  85241. };
  85242. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  85243. };
  85244. return CubeTextureAssetTask;
  85245. }(AbstractAssetTask));
  85246. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  85247. /**
  85248. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  85249. */
  85250. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  85251. __extends(HDRCubeTextureAssetTask, _super);
  85252. /**
  85253. * Creates a new HDRCubeTextureAssetTask object
  85254. * @param name defines the name of the task
  85255. * @param url defines the location of the file to load
  85256. * @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.
  85257. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85258. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85259. * @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)
  85260. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85261. */
  85262. function HDRCubeTextureAssetTask(
  85263. /**
  85264. * Defines the name of the task
  85265. */
  85266. name,
  85267. /**
  85268. * Defines the location of the file to load
  85269. */
  85270. url,
  85271. /**
  85272. * 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.
  85273. */
  85274. size,
  85275. /**
  85276. * Defines if mipmaps should not be generated (default is false)
  85277. */
  85278. noMipmap,
  85279. /**
  85280. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85281. */
  85282. generateHarmonics,
  85283. /**
  85284. * 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)
  85285. */
  85286. useInGammaSpace,
  85287. /**
  85288. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85289. */
  85290. usePMREMGenerator) {
  85291. if (noMipmap === void 0) { noMipmap = false; }
  85292. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85293. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85294. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85295. var _this = _super.call(this, name) || this;
  85296. _this.name = name;
  85297. _this.url = url;
  85298. _this.size = size;
  85299. _this.noMipmap = noMipmap;
  85300. _this.generateHarmonics = generateHarmonics;
  85301. _this.useInGammaSpace = useInGammaSpace;
  85302. _this.usePMREMGenerator = usePMREMGenerator;
  85303. return _this;
  85304. }
  85305. /**
  85306. * Execute the current task
  85307. * @param scene defines the scene where you want your assets to be loaded
  85308. * @param onSuccess is a callback called when the task is successfully executed
  85309. * @param onError is a callback called if an error occurs
  85310. */
  85311. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85312. var onload = function () {
  85313. onSuccess();
  85314. };
  85315. var onerror = function (message, exception) {
  85316. onError(message, exception);
  85317. };
  85318. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  85319. };
  85320. return HDRCubeTextureAssetTask;
  85321. }(AbstractAssetTask));
  85322. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  85323. /**
  85324. * This class can be used to easily import assets into a scene
  85325. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  85326. */
  85327. var AssetsManager = /** @class */ (function () {
  85328. /**
  85329. * Creates a new AssetsManager
  85330. * @param scene defines the scene to work on
  85331. */
  85332. function AssetsManager(scene) {
  85333. this._isLoading = false;
  85334. this._tasks = new Array();
  85335. this._waitingTasksCount = 0;
  85336. this._totalTasksCount = 0;
  85337. /**
  85338. * Observable called when all tasks are processed
  85339. */
  85340. this.onTaskSuccessObservable = new BABYLON.Observable();
  85341. /**
  85342. * Observable called when a task had an error
  85343. */
  85344. this.onTaskErrorObservable = new BABYLON.Observable();
  85345. /**
  85346. * Observable called when a task is successful
  85347. */
  85348. this.onTasksDoneObservable = new BABYLON.Observable();
  85349. /**
  85350. * Observable called when a task is done (whatever the result is)
  85351. */
  85352. this.onProgressObservable = new BABYLON.Observable();
  85353. /**
  85354. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  85355. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  85356. */
  85357. this.useDefaultLoadingScreen = true;
  85358. this._scene = scene;
  85359. }
  85360. /**
  85361. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  85362. * @param taskName defines the name of the new task
  85363. * @param meshesNames defines the name of meshes to load
  85364. * @param rootUrl defines the root url to use to locate files
  85365. * @param sceneFilename defines the filename of the scene file
  85366. * @returns a new {BABYLON.MeshAssetTask} object
  85367. */
  85368. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  85369. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  85370. this._tasks.push(task);
  85371. return task;
  85372. };
  85373. /**
  85374. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  85375. * @param taskName defines the name of the new task
  85376. * @param url defines the url of the file to load
  85377. * @returns a new {BABYLON.TextFileAssetTask} object
  85378. */
  85379. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  85380. var task = new TextFileAssetTask(taskName, url);
  85381. this._tasks.push(task);
  85382. return task;
  85383. };
  85384. /**
  85385. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  85386. * @param taskName defines the name of the new task
  85387. * @param url defines the url of the file to load
  85388. * @returns a new {BABYLON.BinaryFileAssetTask} object
  85389. */
  85390. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  85391. var task = new BinaryFileAssetTask(taskName, url);
  85392. this._tasks.push(task);
  85393. return task;
  85394. };
  85395. /**
  85396. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  85397. * @param taskName defines the name of the new task
  85398. * @param url defines the url of the file to load
  85399. * @returns a new {BABYLON.ImageAssetTask} object
  85400. */
  85401. AssetsManager.prototype.addImageTask = function (taskName, url) {
  85402. var task = new ImageAssetTask(taskName, url);
  85403. this._tasks.push(task);
  85404. return task;
  85405. };
  85406. /**
  85407. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  85408. * @param taskName defines the name of the new task
  85409. * @param url defines the url of the file to load
  85410. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85411. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  85412. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  85413. * @returns a new {BABYLON.TextureAssetTask} object
  85414. */
  85415. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  85416. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85417. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  85418. this._tasks.push(task);
  85419. return task;
  85420. };
  85421. /**
  85422. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  85423. * @param taskName defines the name of the new task
  85424. * @param url defines the url of the file to load
  85425. * @param extensions defines the extension to use to load the cube map (can be null)
  85426. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85427. * @param files defines the list of files to load (can be null)
  85428. * @returns a new {BABYLON.CubeTextureAssetTask} object
  85429. */
  85430. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  85431. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  85432. this._tasks.push(task);
  85433. return task;
  85434. };
  85435. /**
  85436. *
  85437. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  85438. * @param taskName defines the name of the new task
  85439. * @param url defines the url of the file to load
  85440. * @param size defines the size you want for the cubemap (can be null)
  85441. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85442. * @param generateHarmonics defines if you want to automatically generate (true by default)
  85443. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  85444. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  85445. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  85446. */
  85447. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  85448. if (noMipmap === void 0) { noMipmap = false; }
  85449. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85450. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85451. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85452. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  85453. this._tasks.push(task);
  85454. return task;
  85455. };
  85456. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  85457. var _this = this;
  85458. this._waitingTasksCount--;
  85459. try {
  85460. if (task.taskState === AssetTaskState.DONE) {
  85461. // Let's remove successfull tasks
  85462. BABYLON.Tools.SetImmediate(function () {
  85463. var index = _this._tasks.indexOf(task);
  85464. if (index > -1) {
  85465. _this._tasks.splice(index, 1);
  85466. }
  85467. });
  85468. }
  85469. if (this.onProgress) {
  85470. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  85471. }
  85472. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  85473. }
  85474. catch (e) {
  85475. BABYLON.Tools.Error("Error running progress callbacks.");
  85476. console.log(e);
  85477. }
  85478. if (this._waitingTasksCount === 0) {
  85479. try {
  85480. if (this.onFinish) {
  85481. this.onFinish(this._tasks);
  85482. }
  85483. this.onTasksDoneObservable.notifyObservers(this._tasks);
  85484. }
  85485. catch (e) {
  85486. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  85487. console.log(e);
  85488. }
  85489. this._isLoading = false;
  85490. this._scene.getEngine().hideLoadingUI();
  85491. }
  85492. };
  85493. AssetsManager.prototype._runTask = function (task) {
  85494. var _this = this;
  85495. var done = function () {
  85496. try {
  85497. if (_this.onTaskSuccess) {
  85498. _this.onTaskSuccess(task);
  85499. }
  85500. _this.onTaskSuccessObservable.notifyObservers(task);
  85501. _this._decreaseWaitingTasksCount(task);
  85502. }
  85503. catch (e) {
  85504. error("Error executing task success callbacks", e);
  85505. }
  85506. };
  85507. var error = function (message, exception) {
  85508. task._setErrorObject(message, exception);
  85509. if (_this.onTaskError) {
  85510. _this.onTaskError(task);
  85511. }
  85512. _this.onTaskErrorObservable.notifyObservers(task);
  85513. _this._decreaseWaitingTasksCount(task);
  85514. };
  85515. task.run(this._scene, done, error);
  85516. };
  85517. /**
  85518. * Reset the {BABYLON.AssetsManager} and remove all tasks
  85519. * @return the current instance of the {BABYLON.AssetsManager}
  85520. */
  85521. AssetsManager.prototype.reset = function () {
  85522. this._isLoading = false;
  85523. this._tasks = new Array();
  85524. return this;
  85525. };
  85526. /**
  85527. * Start the loading process
  85528. * @return the current instance of the {BABYLON.AssetsManager}
  85529. */
  85530. AssetsManager.prototype.load = function () {
  85531. if (this._isLoading) {
  85532. return this;
  85533. }
  85534. this._isLoading = true;
  85535. this._waitingTasksCount = this._tasks.length;
  85536. this._totalTasksCount = this._tasks.length;
  85537. if (this._waitingTasksCount === 0) {
  85538. this._isLoading = false;
  85539. if (this.onFinish) {
  85540. this.onFinish(this._tasks);
  85541. }
  85542. this.onTasksDoneObservable.notifyObservers(this._tasks);
  85543. return this;
  85544. }
  85545. if (this.useDefaultLoadingScreen) {
  85546. this._scene.getEngine().displayLoadingUI();
  85547. }
  85548. for (var index = 0; index < this._tasks.length; index++) {
  85549. var task = this._tasks[index];
  85550. this._runTask(task);
  85551. }
  85552. return this;
  85553. };
  85554. return AssetsManager;
  85555. }());
  85556. BABYLON.AssetsManager = AssetsManager;
  85557. })(BABYLON || (BABYLON = {}));
  85558. //# sourceMappingURL=babylon.assetsManager.js.map
  85559. var BABYLON;
  85560. (function (BABYLON) {
  85561. var serializedGeometries = [];
  85562. var serializeGeometry = function (geometry, serializationGeometries) {
  85563. if (serializedGeometries[geometry.id]) {
  85564. return;
  85565. }
  85566. if (geometry.doNotSerialize) {
  85567. return;
  85568. }
  85569. if (geometry instanceof BABYLON.BoxGeometry) {
  85570. serializationGeometries.boxes.push(geometry.serialize());
  85571. }
  85572. else if (geometry instanceof BABYLON.SphereGeometry) {
  85573. serializationGeometries.spheres.push(geometry.serialize());
  85574. }
  85575. else if (geometry instanceof BABYLON.CylinderGeometry) {
  85576. serializationGeometries.cylinders.push(geometry.serialize());
  85577. }
  85578. else if (geometry instanceof BABYLON.TorusGeometry) {
  85579. serializationGeometries.toruses.push(geometry.serialize());
  85580. }
  85581. else if (geometry instanceof BABYLON.GroundGeometry) {
  85582. serializationGeometries.grounds.push(geometry.serialize());
  85583. }
  85584. else if (geometry instanceof BABYLON.Plane) {
  85585. serializationGeometries.planes.push(geometry.serialize());
  85586. }
  85587. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  85588. serializationGeometries.torusKnots.push(geometry.serialize());
  85589. }
  85590. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  85591. throw new Error("Unknown primitive type");
  85592. }
  85593. else {
  85594. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  85595. }
  85596. serializedGeometries[geometry.id] = true;
  85597. };
  85598. var serializeMesh = function (mesh, serializationScene) {
  85599. var serializationObject = {};
  85600. // Geometry
  85601. var geometry = mesh._geometry;
  85602. if (geometry) {
  85603. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  85604. // 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
  85605. serializeGeometry(geometry, serializationScene.geometries);
  85606. }
  85607. }
  85608. // Custom
  85609. if (mesh.serialize) {
  85610. mesh.serialize(serializationObject);
  85611. }
  85612. return serializationObject;
  85613. };
  85614. var finalizeSingleMesh = function (mesh, serializationObject) {
  85615. //only works if the mesh is already loaded
  85616. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  85617. //serialize material
  85618. if (mesh.material) {
  85619. if (mesh.material instanceof BABYLON.StandardMaterial) {
  85620. serializationObject.materials = serializationObject.materials || [];
  85621. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85622. serializationObject.materials.push(mesh.material.serialize());
  85623. }
  85624. }
  85625. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  85626. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  85627. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85628. serializationObject.multiMaterials.push(mesh.material.serialize());
  85629. }
  85630. }
  85631. }
  85632. //serialize geometry
  85633. var geometry = mesh._geometry;
  85634. if (geometry) {
  85635. if (!serializationObject.geometries) {
  85636. serializationObject.geometries = {};
  85637. serializationObject.geometries.boxes = [];
  85638. serializationObject.geometries.spheres = [];
  85639. serializationObject.geometries.cylinders = [];
  85640. serializationObject.geometries.toruses = [];
  85641. serializationObject.geometries.grounds = [];
  85642. serializationObject.geometries.planes = [];
  85643. serializationObject.geometries.torusKnots = [];
  85644. serializationObject.geometries.vertexData = [];
  85645. }
  85646. serializeGeometry(geometry, serializationObject.geometries);
  85647. }
  85648. // Skeletons
  85649. if (mesh.skeleton) {
  85650. serializationObject.skeletons = serializationObject.skeletons || [];
  85651. serializationObject.skeletons.push(mesh.skeleton.serialize());
  85652. }
  85653. //serialize the actual mesh
  85654. serializationObject.meshes = serializationObject.meshes || [];
  85655. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  85656. }
  85657. };
  85658. var SceneSerializer = /** @class */ (function () {
  85659. function SceneSerializer() {
  85660. }
  85661. SceneSerializer.ClearCache = function () {
  85662. serializedGeometries = [];
  85663. };
  85664. SceneSerializer.Serialize = function (scene) {
  85665. var serializationObject = {};
  85666. SceneSerializer.ClearCache();
  85667. // Scene
  85668. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  85669. serializationObject.autoClear = scene.autoClear;
  85670. serializationObject.clearColor = scene.clearColor.asArray();
  85671. serializationObject.ambientColor = scene.ambientColor.asArray();
  85672. serializationObject.gravity = scene.gravity.asArray();
  85673. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  85674. serializationObject.workerCollisions = scene.workerCollisions;
  85675. // Fog
  85676. if (scene.fogMode && scene.fogMode !== 0) {
  85677. serializationObject.fogMode = scene.fogMode;
  85678. serializationObject.fogColor = scene.fogColor.asArray();
  85679. serializationObject.fogStart = scene.fogStart;
  85680. serializationObject.fogEnd = scene.fogEnd;
  85681. serializationObject.fogDensity = scene.fogDensity;
  85682. }
  85683. //Physics
  85684. if (scene.isPhysicsEnabled()) {
  85685. var physicEngine = scene.getPhysicsEngine();
  85686. if (physicEngine) {
  85687. serializationObject.physicsEnabled = true;
  85688. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  85689. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  85690. }
  85691. }
  85692. // Metadata
  85693. if (scene.metadata) {
  85694. serializationObject.metadata = scene.metadata;
  85695. }
  85696. // Morph targets
  85697. serializationObject.morphTargetManagers = [];
  85698. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  85699. var abstractMesh = _a[_i];
  85700. var manager = abstractMesh.morphTargetManager;
  85701. if (manager) {
  85702. serializationObject.morphTargetManagers.push(manager.serialize());
  85703. }
  85704. }
  85705. // Lights
  85706. serializationObject.lights = [];
  85707. var index;
  85708. var light;
  85709. for (index = 0; index < scene.lights.length; index++) {
  85710. light = scene.lights[index];
  85711. if (!light.doNotSerialize) {
  85712. serializationObject.lights.push(light.serialize());
  85713. }
  85714. }
  85715. // Cameras
  85716. serializationObject.cameras = [];
  85717. for (index = 0; index < scene.cameras.length; index++) {
  85718. var camera = scene.cameras[index];
  85719. if (!camera.doNotSerialize) {
  85720. serializationObject.cameras.push(camera.serialize());
  85721. }
  85722. }
  85723. if (scene.activeCamera) {
  85724. serializationObject.activeCameraID = scene.activeCamera.id;
  85725. }
  85726. // Animations
  85727. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  85728. // Materials
  85729. serializationObject.materials = [];
  85730. serializationObject.multiMaterials = [];
  85731. var material;
  85732. for (index = 0; index < scene.materials.length; index++) {
  85733. material = scene.materials[index];
  85734. if (!material.doNotSerialize) {
  85735. serializationObject.materials.push(material.serialize());
  85736. }
  85737. }
  85738. // MultiMaterials
  85739. serializationObject.multiMaterials = [];
  85740. for (index = 0; index < scene.multiMaterials.length; index++) {
  85741. var multiMaterial = scene.multiMaterials[index];
  85742. serializationObject.multiMaterials.push(multiMaterial.serialize());
  85743. }
  85744. // Environment texture
  85745. if (scene.environmentTexture) {
  85746. serializationObject.environmentTexture = scene.environmentTexture.name;
  85747. }
  85748. // Skeletons
  85749. serializationObject.skeletons = [];
  85750. for (index = 0; index < scene.skeletons.length; index++) {
  85751. var skeleton = scene.skeletons[index];
  85752. if (!skeleton.doNotSerialize) {
  85753. serializationObject.skeletons.push(skeleton.serialize());
  85754. }
  85755. }
  85756. // Transform nodes
  85757. serializationObject.transformNodes = [];
  85758. for (index = 0; index < scene.transformNodes.length; index++) {
  85759. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  85760. }
  85761. // Geometries
  85762. serializationObject.geometries = {};
  85763. serializationObject.geometries.boxes = [];
  85764. serializationObject.geometries.spheres = [];
  85765. serializationObject.geometries.cylinders = [];
  85766. serializationObject.geometries.toruses = [];
  85767. serializationObject.geometries.grounds = [];
  85768. serializationObject.geometries.planes = [];
  85769. serializationObject.geometries.torusKnots = [];
  85770. serializationObject.geometries.vertexData = [];
  85771. serializedGeometries = [];
  85772. var geometries = scene.getGeometries();
  85773. for (index = 0; index < geometries.length; index++) {
  85774. var geometry = geometries[index];
  85775. if (geometry.isReady()) {
  85776. serializeGeometry(geometry, serializationObject.geometries);
  85777. }
  85778. }
  85779. // Meshes
  85780. serializationObject.meshes = [];
  85781. for (index = 0; index < scene.meshes.length; index++) {
  85782. var abstractMesh = scene.meshes[index];
  85783. if (abstractMesh instanceof BABYLON.Mesh) {
  85784. var mesh = abstractMesh;
  85785. if (!mesh.doNotSerialize) {
  85786. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  85787. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  85788. }
  85789. }
  85790. }
  85791. }
  85792. // Particles Systems
  85793. serializationObject.particleSystems = [];
  85794. for (index = 0; index < scene.particleSystems.length; index++) {
  85795. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  85796. }
  85797. // Lens flares
  85798. serializationObject.lensFlareSystems = [];
  85799. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  85800. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  85801. }
  85802. // Shadows
  85803. serializationObject.shadowGenerators = [];
  85804. for (index = 0; index < scene.lights.length; index++) {
  85805. light = scene.lights[index];
  85806. var shadowGenerator = light.getShadowGenerator();
  85807. if (shadowGenerator) {
  85808. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  85809. }
  85810. }
  85811. // Action Manager
  85812. if (scene.actionManager) {
  85813. serializationObject.actions = scene.actionManager.serialize("scene");
  85814. }
  85815. // Audio
  85816. serializationObject.sounds = [];
  85817. for (index = 0; index < scene.soundTracks.length; index++) {
  85818. var soundtrack = scene.soundTracks[index];
  85819. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  85820. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  85821. }
  85822. }
  85823. return serializationObject;
  85824. };
  85825. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  85826. if (withParents === void 0) { withParents = false; }
  85827. if (withChildren === void 0) { withChildren = false; }
  85828. var serializationObject = {};
  85829. SceneSerializer.ClearCache();
  85830. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  85831. if (withParents || withChildren) {
  85832. //deliberate for loop! not for each, appended should be processed as well.
  85833. for (var i = 0; i < toSerialize.length; ++i) {
  85834. if (withChildren) {
  85835. toSerialize[i].getDescendants().forEach(function (node) {
  85836. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  85837. toSerialize.push(node);
  85838. }
  85839. });
  85840. }
  85841. //make sure the array doesn't contain the object already
  85842. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  85843. toSerialize.push(toSerialize[i].parent);
  85844. }
  85845. }
  85846. }
  85847. toSerialize.forEach(function (mesh) {
  85848. finalizeSingleMesh(mesh, serializationObject);
  85849. });
  85850. return serializationObject;
  85851. };
  85852. return SceneSerializer;
  85853. }());
  85854. BABYLON.SceneSerializer = SceneSerializer;
  85855. })(BABYLON || (BABYLON = {}));
  85856. //# sourceMappingURL=babylon.sceneSerializer.js.map
  85857. var BABYLON;
  85858. (function (BABYLON) {
  85859. var ReflectionProbe = /** @class */ (function () {
  85860. function ReflectionProbe(name, size, scene, generateMipMaps) {
  85861. if (generateMipMaps === void 0) { generateMipMaps = true; }
  85862. var _this = this;
  85863. this.name = name;
  85864. this._viewMatrix = BABYLON.Matrix.Identity();
  85865. this._target = BABYLON.Vector3.Zero();
  85866. this._add = BABYLON.Vector3.Zero();
  85867. this.invertYAxis = false;
  85868. this.position = BABYLON.Vector3.Zero();
  85869. this._scene = scene;
  85870. this._scene.reflectionProbes.push(this);
  85871. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  85872. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  85873. switch (faceIndex) {
  85874. case 0:
  85875. _this._add.copyFromFloats(1, 0, 0);
  85876. break;
  85877. case 1:
  85878. _this._add.copyFromFloats(-1, 0, 0);
  85879. break;
  85880. case 2:
  85881. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  85882. break;
  85883. case 3:
  85884. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  85885. break;
  85886. case 4:
  85887. _this._add.copyFromFloats(0, 0, 1);
  85888. break;
  85889. case 5:
  85890. _this._add.copyFromFloats(0, 0, -1);
  85891. break;
  85892. }
  85893. if (_this._attachedMesh) {
  85894. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  85895. }
  85896. _this.position.addToRef(_this._add, _this._target);
  85897. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  85898. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  85899. scene._forcedViewPosition = _this.position;
  85900. });
  85901. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  85902. scene._forcedViewPosition = null;
  85903. scene.updateTransformMatrix(true);
  85904. });
  85905. if (scene.activeCamera) {
  85906. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  85907. }
  85908. }
  85909. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  85910. get: function () {
  85911. return this._renderTargetTexture.samples;
  85912. },
  85913. set: function (value) {
  85914. this._renderTargetTexture.samples = value;
  85915. },
  85916. enumerable: true,
  85917. configurable: true
  85918. });
  85919. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  85920. get: function () {
  85921. return this._renderTargetTexture.refreshRate;
  85922. },
  85923. set: function (value) {
  85924. this._renderTargetTexture.refreshRate = value;
  85925. },
  85926. enumerable: true,
  85927. configurable: true
  85928. });
  85929. ReflectionProbe.prototype.getScene = function () {
  85930. return this._scene;
  85931. };
  85932. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  85933. get: function () {
  85934. return this._renderTargetTexture;
  85935. },
  85936. enumerable: true,
  85937. configurable: true
  85938. });
  85939. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  85940. get: function () {
  85941. return this._renderTargetTexture.renderList;
  85942. },
  85943. enumerable: true,
  85944. configurable: true
  85945. });
  85946. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  85947. this._attachedMesh = mesh;
  85948. };
  85949. /**
  85950. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  85951. *
  85952. * @param renderingGroupId The rendering group id corresponding to its index
  85953. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  85954. */
  85955. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  85956. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  85957. };
  85958. ReflectionProbe.prototype.dispose = function () {
  85959. var index = this._scene.reflectionProbes.indexOf(this);
  85960. if (index !== -1) {
  85961. // Remove from the scene if found
  85962. this._scene.reflectionProbes.splice(index, 1);
  85963. }
  85964. if (this._renderTargetTexture) {
  85965. this._renderTargetTexture.dispose();
  85966. this._renderTargetTexture = null;
  85967. }
  85968. };
  85969. return ReflectionProbe;
  85970. }());
  85971. BABYLON.ReflectionProbe = ReflectionProbe;
  85972. })(BABYLON || (BABYLON = {}));
  85973. //# sourceMappingURL=babylon.reflectionProbe.js.map
  85974. var BABYLON;
  85975. (function (BABYLON) {
  85976. var Layer = /** @class */ (function () {
  85977. function Layer(name, imgUrl, scene, isBackground, color) {
  85978. this.name = name;
  85979. this.scale = new BABYLON.Vector2(1, 1);
  85980. this.offset = new BABYLON.Vector2(0, 0);
  85981. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  85982. this.layerMask = 0x0FFFFFFF;
  85983. this._vertexBuffers = {};
  85984. // Events
  85985. /**
  85986. * An event triggered when the layer is disposed.
  85987. * @type {BABYLON.Observable}
  85988. */
  85989. this.onDisposeObservable = new BABYLON.Observable();
  85990. /**
  85991. * An event triggered before rendering the scene
  85992. * @type {BABYLON.Observable}
  85993. */
  85994. this.onBeforeRenderObservable = new BABYLON.Observable();
  85995. /**
  85996. * An event triggered after rendering the scene
  85997. * @type {BABYLON.Observable}
  85998. */
  85999. this.onAfterRenderObservable = new BABYLON.Observable();
  86000. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  86001. this.isBackground = isBackground === undefined ? true : isBackground;
  86002. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  86003. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  86004. this._scene.layers.push(this);
  86005. var engine = this._scene.getEngine();
  86006. // VBO
  86007. var vertices = [];
  86008. vertices.push(1, 1);
  86009. vertices.push(-1, 1);
  86010. vertices.push(-1, -1);
  86011. vertices.push(1, -1);
  86012. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86013. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86014. this._createIndexBuffer();
  86015. // Effects
  86016. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  86017. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  86018. }
  86019. Object.defineProperty(Layer.prototype, "onDispose", {
  86020. set: function (callback) {
  86021. if (this._onDisposeObserver) {
  86022. this.onDisposeObservable.remove(this._onDisposeObserver);
  86023. }
  86024. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86025. },
  86026. enumerable: true,
  86027. configurable: true
  86028. });
  86029. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  86030. set: function (callback) {
  86031. if (this._onBeforeRenderObserver) {
  86032. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  86033. }
  86034. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  86035. },
  86036. enumerable: true,
  86037. configurable: true
  86038. });
  86039. Object.defineProperty(Layer.prototype, "onAfterRender", {
  86040. set: function (callback) {
  86041. if (this._onAfterRenderObserver) {
  86042. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86043. }
  86044. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  86045. },
  86046. enumerable: true,
  86047. configurable: true
  86048. });
  86049. Layer.prototype._createIndexBuffer = function () {
  86050. var engine = this._scene.getEngine();
  86051. // Indices
  86052. var indices = [];
  86053. indices.push(0);
  86054. indices.push(1);
  86055. indices.push(2);
  86056. indices.push(0);
  86057. indices.push(2);
  86058. indices.push(3);
  86059. this._indexBuffer = engine.createIndexBuffer(indices);
  86060. };
  86061. Layer.prototype._rebuild = function () {
  86062. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86063. if (vb) {
  86064. vb._rebuild();
  86065. }
  86066. this._createIndexBuffer();
  86067. };
  86068. Layer.prototype.render = function () {
  86069. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  86070. // Check
  86071. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  86072. return;
  86073. var engine = this._scene.getEngine();
  86074. this.onBeforeRenderObservable.notifyObservers(this);
  86075. // Render
  86076. engine.enableEffect(currentEffect);
  86077. engine.setState(false);
  86078. // Texture
  86079. currentEffect.setTexture("textureSampler", this.texture);
  86080. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  86081. // Color
  86082. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  86083. // Scale / offset
  86084. currentEffect.setVector2("offset", this.offset);
  86085. currentEffect.setVector2("scale", this.scale);
  86086. // VBOs
  86087. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86088. // Draw order
  86089. if (!this.alphaTest) {
  86090. engine.setAlphaMode(this.alphaBlendingMode);
  86091. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86092. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86093. }
  86094. else {
  86095. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86096. }
  86097. this.onAfterRenderObservable.notifyObservers(this);
  86098. };
  86099. Layer.prototype.dispose = function () {
  86100. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86101. if (vertexBuffer) {
  86102. vertexBuffer.dispose();
  86103. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86104. }
  86105. if (this._indexBuffer) {
  86106. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86107. this._indexBuffer = null;
  86108. }
  86109. if (this.texture) {
  86110. this.texture.dispose();
  86111. this.texture = null;
  86112. }
  86113. // Remove from scene
  86114. var index = this._scene.layers.indexOf(this);
  86115. this._scene.layers.splice(index, 1);
  86116. // Callback
  86117. this.onDisposeObservable.notifyObservers(this);
  86118. this.onDisposeObservable.clear();
  86119. this.onAfterRenderObservable.clear();
  86120. this.onBeforeRenderObservable.clear();
  86121. };
  86122. return Layer;
  86123. }());
  86124. BABYLON.Layer = Layer;
  86125. })(BABYLON || (BABYLON = {}));
  86126. //# sourceMappingURL=babylon.layer.js.map
  86127. var BABYLON;
  86128. (function (BABYLON) {
  86129. var TextureTools = /** @class */ (function () {
  86130. function TextureTools() {
  86131. }
  86132. /**
  86133. * Uses the GPU to create a copy texture rescaled at a given size
  86134. * @param texture Texture to copy from
  86135. * @param width Desired width
  86136. * @param height Desired height
  86137. * @return Generated texture
  86138. */
  86139. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  86140. if (useBilinearMode === void 0) { useBilinearMode = true; }
  86141. var scene = texture.getScene();
  86142. var engine = scene.getEngine();
  86143. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  86144. rtt.wrapU = texture.wrapU;
  86145. rtt.wrapV = texture.wrapV;
  86146. rtt.uOffset = texture.uOffset;
  86147. rtt.vOffset = texture.vOffset;
  86148. rtt.uScale = texture.uScale;
  86149. rtt.vScale = texture.vScale;
  86150. rtt.uAng = texture.uAng;
  86151. rtt.vAng = texture.vAng;
  86152. rtt.wAng = texture.wAng;
  86153. rtt.coordinatesIndex = texture.coordinatesIndex;
  86154. rtt.level = texture.level;
  86155. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  86156. rtt._texture.isReady = false;
  86157. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86158. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86159. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86160. passPostProcess.getEffect().executeWhenCompiled(function () {
  86161. passPostProcess.onApply = function (effect) {
  86162. effect.setTexture("textureSampler", texture);
  86163. };
  86164. var internalTexture = rtt.getInternalTexture();
  86165. if (internalTexture) {
  86166. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  86167. engine.unBindFramebuffer(internalTexture);
  86168. rtt.disposeFramebufferObjects();
  86169. passPostProcess.dispose();
  86170. internalTexture.isReady = true;
  86171. }
  86172. });
  86173. return rtt;
  86174. };
  86175. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  86176. if (!scene._environmentBRDFTexture) {
  86177. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86178. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86179. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86180. scene._environmentBRDFTexture = texture;
  86181. }
  86182. return scene._environmentBRDFTexture;
  86183. };
  86184. 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=";
  86185. return TextureTools;
  86186. }());
  86187. BABYLON.TextureTools = TextureTools;
  86188. })(BABYLON || (BABYLON = {}));
  86189. //# sourceMappingURL=babylon.textureTools.js.map
  86190. var BABYLON;
  86191. (function (BABYLON) {
  86192. var FramingBehavior = /** @class */ (function () {
  86193. function FramingBehavior() {
  86194. this._mode = FramingBehavior.FitFrustumSidesMode;
  86195. this._radiusScale = 1.0;
  86196. this._positionScale = 0.5;
  86197. this._defaultElevation = 0.3;
  86198. this._elevationReturnTime = 1500;
  86199. this._elevationReturnWaitTime = 1000;
  86200. this._zoomStopsAnimation = false;
  86201. this._framingTime = 1500;
  86202. this._isPointerDown = false;
  86203. this._lastInteractionTime = -Infinity;
  86204. // Framing control
  86205. this._animatables = new Array();
  86206. this._betaIsAnimating = false;
  86207. }
  86208. Object.defineProperty(FramingBehavior.prototype, "name", {
  86209. get: function () {
  86210. return "Framing";
  86211. },
  86212. enumerable: true,
  86213. configurable: true
  86214. });
  86215. Object.defineProperty(FramingBehavior.prototype, "mode", {
  86216. /**
  86217. * Gets current mode used by the behavior.
  86218. */
  86219. get: function () {
  86220. return this._mode;
  86221. },
  86222. /**
  86223. * Sets the current mode used by the behavior
  86224. */
  86225. set: function (mode) {
  86226. this._mode = mode;
  86227. },
  86228. enumerable: true,
  86229. configurable: true
  86230. });
  86231. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  86232. /**
  86233. * Gets the scale applied to the radius
  86234. */
  86235. get: function () {
  86236. return this._radiusScale;
  86237. },
  86238. /**
  86239. * Sets the scale applied to the radius (1 by default)
  86240. */
  86241. set: function (radius) {
  86242. this._radiusScale = radius;
  86243. },
  86244. enumerable: true,
  86245. configurable: true
  86246. });
  86247. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  86248. /**
  86249. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86250. */
  86251. get: function () {
  86252. return this._positionScale;
  86253. },
  86254. /**
  86255. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86256. */
  86257. set: function (scale) {
  86258. this._positionScale = scale;
  86259. },
  86260. enumerable: true,
  86261. configurable: true
  86262. });
  86263. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  86264. /**
  86265. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86266. * behaviour is triggered, in radians.
  86267. */
  86268. get: function () {
  86269. return this._defaultElevation;
  86270. },
  86271. /**
  86272. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86273. * behaviour is triggered, in radians.
  86274. */
  86275. set: function (elevation) {
  86276. this._defaultElevation = elevation;
  86277. },
  86278. enumerable: true,
  86279. configurable: true
  86280. });
  86281. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  86282. /**
  86283. * Gets the time (in milliseconds) taken to return to the default beta position.
  86284. * Negative value indicates camera should not return to default.
  86285. */
  86286. get: function () {
  86287. return this._elevationReturnTime;
  86288. },
  86289. /**
  86290. * Sets the time (in milliseconds) taken to return to the default beta position.
  86291. * Negative value indicates camera should not return to default.
  86292. */
  86293. set: function (speed) {
  86294. this._elevationReturnTime = speed;
  86295. },
  86296. enumerable: true,
  86297. configurable: true
  86298. });
  86299. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  86300. /**
  86301. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86302. */
  86303. get: function () {
  86304. return this._elevationReturnWaitTime;
  86305. },
  86306. /**
  86307. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86308. */
  86309. set: function (time) {
  86310. this._elevationReturnWaitTime = time;
  86311. },
  86312. enumerable: true,
  86313. configurable: true
  86314. });
  86315. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  86316. /**
  86317. * Gets the flag that indicates if user zooming should stop animation.
  86318. */
  86319. get: function () {
  86320. return this._zoomStopsAnimation;
  86321. },
  86322. /**
  86323. * Sets the flag that indicates if user zooming should stop animation.
  86324. */
  86325. set: function (flag) {
  86326. this._zoomStopsAnimation = flag;
  86327. },
  86328. enumerable: true,
  86329. configurable: true
  86330. });
  86331. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  86332. /**
  86333. * Gets the transition time when framing the mesh, in milliseconds
  86334. */
  86335. get: function () {
  86336. return this._framingTime;
  86337. },
  86338. /**
  86339. * Sets the transition time when framing the mesh, in milliseconds
  86340. */
  86341. set: function (time) {
  86342. this._framingTime = time;
  86343. },
  86344. enumerable: true,
  86345. configurable: true
  86346. });
  86347. FramingBehavior.prototype.init = function () {
  86348. // Do notihng
  86349. };
  86350. FramingBehavior.prototype.attach = function (camera) {
  86351. var _this = this;
  86352. this._attachedCamera = camera;
  86353. var scene = this._attachedCamera.getScene();
  86354. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  86355. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  86356. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  86357. _this._isPointerDown = true;
  86358. return;
  86359. }
  86360. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  86361. _this._isPointerDown = false;
  86362. }
  86363. });
  86364. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86365. if (mesh) {
  86366. _this.zoomOnMesh(mesh);
  86367. }
  86368. });
  86369. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86370. // Stop the animation if there is user interaction and the animation should stop for this interaction
  86371. _this._applyUserInteraction();
  86372. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  86373. // back to the default position after a given timeout
  86374. _this._maintainCameraAboveGround();
  86375. });
  86376. };
  86377. FramingBehavior.prototype.detach = function () {
  86378. if (!this._attachedCamera) {
  86379. return;
  86380. }
  86381. var scene = this._attachedCamera.getScene();
  86382. if (this._onPrePointerObservableObserver) {
  86383. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  86384. }
  86385. if (this._onAfterCheckInputsObserver) {
  86386. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86387. }
  86388. if (this._onMeshTargetChangedObserver) {
  86389. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86390. }
  86391. this._attachedCamera = null;
  86392. };
  86393. /**
  86394. * Targets the given mesh and updates zoom level accordingly.
  86395. * @param mesh The mesh to target.
  86396. * @param radius Optional. If a cached radius position already exists, overrides default.
  86397. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86398. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86399. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86400. */
  86401. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86402. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86403. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86404. mesh.computeWorldMatrix(true);
  86405. var boundingBox = mesh.getBoundingInfo().boundingBox;
  86406. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  86407. };
  86408. /**
  86409. * Targets the given mesh with its children and updates zoom level accordingly.
  86410. * @param mesh The mesh to target.
  86411. * @param radius Optional. If a cached radius position already exists, overrides default.
  86412. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86413. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86414. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86415. */
  86416. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86417. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86418. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86419. mesh.computeWorldMatrix(true);
  86420. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  86421. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  86422. };
  86423. /**
  86424. * Targets the given meshes with their children and updates zoom level accordingly.
  86425. * @param meshes The mesh to target.
  86426. * @param radius Optional. If a cached radius position already exists, overrides default.
  86427. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86428. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86429. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86430. */
  86431. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  86432. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86433. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86434. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  86435. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  86436. for (var i = 0; i < meshes.length; i++) {
  86437. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  86438. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  86439. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  86440. }
  86441. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  86442. };
  86443. /**
  86444. * Targets the given mesh and updates zoom level accordingly.
  86445. * @param mesh The mesh to target.
  86446. * @param radius Optional. If a cached radius position already exists, overrides default.
  86447. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86448. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86449. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86450. */
  86451. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  86452. var _this = this;
  86453. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86454. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86455. var zoomTarget;
  86456. if (!this._attachedCamera) {
  86457. return;
  86458. }
  86459. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  86460. var bottom = minimumWorld.y;
  86461. var top = maximumWorld.y;
  86462. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  86463. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  86464. if (focusOnOriginXZ) {
  86465. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  86466. }
  86467. else {
  86468. var centerWorld = minimumWorld.add(radiusWorld);
  86469. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  86470. }
  86471. if (!this._vectorTransition) {
  86472. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  86473. }
  86474. this._betaIsAnimating = true;
  86475. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  86476. if (animatable) {
  86477. this._animatables.push(animatable);
  86478. }
  86479. // sets the radius and lower radius bounds
  86480. // Small delta ensures camera is not always at lower zoom limit.
  86481. var radius = 0;
  86482. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  86483. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  86484. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  86485. radius = position;
  86486. }
  86487. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  86488. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  86489. if (this._attachedCamera.lowerRadiusLimit === null) {
  86490. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  86491. }
  86492. }
  86493. // Set sensibilities
  86494. var extend = maximumWorld.subtract(minimumWorld).length();
  86495. this._attachedCamera.panningSensibility = 5000 / extend;
  86496. this._attachedCamera.wheelPrecision = 100 / radius;
  86497. // transition to new radius
  86498. if (!this._radiusTransition) {
  86499. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  86500. }
  86501. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  86502. if (onAnimationEnd) {
  86503. onAnimationEnd();
  86504. }
  86505. if (_this._attachedCamera) {
  86506. _this._attachedCamera.storeState();
  86507. }
  86508. });
  86509. if (animatable) {
  86510. this._animatables.push(animatable);
  86511. }
  86512. };
  86513. /**
  86514. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  86515. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  86516. * frustum width.
  86517. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  86518. * to fully enclose the mesh in the viewing frustum.
  86519. */
  86520. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  86521. var size = maximumWorld.subtract(minimumWorld);
  86522. var boxVectorGlobalDiagonal = size.length();
  86523. var frustumSlope = this._getFrustumSlope();
  86524. // Formula for setting distance
  86525. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  86526. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  86527. // Horizon distance
  86528. var radius = radiusWithoutFraming * this._radiusScale;
  86529. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  86530. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  86531. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  86532. var camera = this._attachedCamera;
  86533. if (!camera) {
  86534. return 0;
  86535. }
  86536. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  86537. // Don't exceed the requested limit
  86538. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  86539. }
  86540. // Don't exceed the upper radius limit
  86541. if (camera.upperRadiusLimit) {
  86542. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  86543. }
  86544. return distance;
  86545. };
  86546. /**
  86547. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  86548. * is automatically returned to its default position (expected to be above ground plane).
  86549. */
  86550. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  86551. var _this = this;
  86552. if (this._elevationReturnTime < 0) {
  86553. return;
  86554. }
  86555. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  86556. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  86557. var limitBeta = Math.PI * 0.5;
  86558. // Bring the camera back up if below the ground plane
  86559. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  86560. this._betaIsAnimating = true;
  86561. //Transition to new position
  86562. this.stopAllAnimations();
  86563. if (!this._betaTransition) {
  86564. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  86565. }
  86566. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  86567. _this._clearAnimationLocks();
  86568. _this.stopAllAnimations();
  86569. });
  86570. if (animatabe) {
  86571. this._animatables.push(animatabe);
  86572. }
  86573. }
  86574. };
  86575. /**
  86576. * Returns the frustum slope based on the canvas ratio and camera FOV
  86577. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  86578. */
  86579. FramingBehavior.prototype._getFrustumSlope = function () {
  86580. // Calculate the viewport ratio
  86581. // Aspect Ratio is Height/Width.
  86582. var camera = this._attachedCamera;
  86583. if (!camera) {
  86584. return BABYLON.Vector2.Zero();
  86585. }
  86586. var engine = camera.getScene().getEngine();
  86587. var aspectRatio = engine.getAspectRatio(camera);
  86588. // Camera FOV is the vertical field of view (top-bottom) in radians.
  86589. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  86590. var frustumSlopeY = Math.tan(camera.fov / 2);
  86591. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  86592. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  86593. // along the forward vector.
  86594. var frustumSlopeX = frustumSlopeY * aspectRatio;
  86595. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  86596. };
  86597. /**
  86598. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  86599. */
  86600. FramingBehavior.prototype._clearAnimationLocks = function () {
  86601. this._betaIsAnimating = false;
  86602. };
  86603. /**
  86604. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  86605. */
  86606. FramingBehavior.prototype._applyUserInteraction = function () {
  86607. if (this.isUserIsMoving) {
  86608. this._lastInteractionTime = BABYLON.Tools.Now;
  86609. this.stopAllAnimations();
  86610. this._clearAnimationLocks();
  86611. }
  86612. };
  86613. /**
  86614. * Stops and removes all animations that have been applied to the camera
  86615. */
  86616. FramingBehavior.prototype.stopAllAnimations = function () {
  86617. if (this._attachedCamera) {
  86618. this._attachedCamera.animations = [];
  86619. }
  86620. while (this._animatables.length) {
  86621. if (this._animatables[0]) {
  86622. this._animatables[0].onAnimationEnd = null;
  86623. this._animatables[0].stop();
  86624. }
  86625. this._animatables.shift();
  86626. }
  86627. };
  86628. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  86629. /**
  86630. * Gets a value indicating if the user is moving the camera
  86631. */
  86632. get: function () {
  86633. if (!this._attachedCamera) {
  86634. return false;
  86635. }
  86636. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  86637. this._attachedCamera.inertialBetaOffset !== 0 ||
  86638. this._attachedCamera.inertialRadiusOffset !== 0 ||
  86639. this._attachedCamera.inertialPanningX !== 0 ||
  86640. this._attachedCamera.inertialPanningY !== 0 ||
  86641. this._isPointerDown;
  86642. },
  86643. enumerable: true,
  86644. configurable: true
  86645. });
  86646. /**
  86647. * The easing function used by animations
  86648. */
  86649. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  86650. /**
  86651. * The easing mode used by animations
  86652. */
  86653. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  86654. // Statics
  86655. /**
  86656. * The camera can move all the way towards the mesh.
  86657. */
  86658. FramingBehavior.IgnoreBoundsSizeMode = 0;
  86659. /**
  86660. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  86661. */
  86662. FramingBehavior.FitFrustumSidesMode = 1;
  86663. return FramingBehavior;
  86664. }());
  86665. BABYLON.FramingBehavior = FramingBehavior;
  86666. })(BABYLON || (BABYLON = {}));
  86667. //# sourceMappingURL=babylon.framingBehavior.js.map
  86668. var BABYLON;
  86669. (function (BABYLON) {
  86670. /**
  86671. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  86672. */
  86673. var BouncingBehavior = /** @class */ (function () {
  86674. function BouncingBehavior() {
  86675. /**
  86676. * The duration of the animation, in milliseconds
  86677. */
  86678. this.transitionDuration = 450;
  86679. /**
  86680. * Length of the distance animated by the transition when lower radius is reached
  86681. */
  86682. this.lowerRadiusTransitionRange = 2;
  86683. /**
  86684. * Length of the distance animated by the transition when upper radius is reached
  86685. */
  86686. this.upperRadiusTransitionRange = -2;
  86687. this._autoTransitionRange = false;
  86688. // Animations
  86689. this._radiusIsAnimating = false;
  86690. this._radiusBounceTransition = null;
  86691. this._animatables = new Array();
  86692. }
  86693. Object.defineProperty(BouncingBehavior.prototype, "name", {
  86694. get: function () {
  86695. return "Bouncing";
  86696. },
  86697. enumerable: true,
  86698. configurable: true
  86699. });
  86700. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  86701. /**
  86702. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  86703. */
  86704. get: function () {
  86705. return this._autoTransitionRange;
  86706. },
  86707. /**
  86708. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  86709. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  86710. */
  86711. set: function (value) {
  86712. var _this = this;
  86713. if (this._autoTransitionRange === value) {
  86714. return;
  86715. }
  86716. this._autoTransitionRange = value;
  86717. var camera = this._attachedCamera;
  86718. if (!camera) {
  86719. return;
  86720. }
  86721. if (value) {
  86722. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86723. if (!mesh) {
  86724. return;
  86725. }
  86726. mesh.computeWorldMatrix(true);
  86727. var diagonal = mesh.getBoundingInfo().diagonalLength;
  86728. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  86729. _this.upperRadiusTransitionRange = diagonal * 0.05;
  86730. });
  86731. }
  86732. else if (this._onMeshTargetChangedObserver) {
  86733. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86734. }
  86735. },
  86736. enumerable: true,
  86737. configurable: true
  86738. });
  86739. BouncingBehavior.prototype.init = function () {
  86740. // Do notihng
  86741. };
  86742. BouncingBehavior.prototype.attach = function (camera) {
  86743. var _this = this;
  86744. this._attachedCamera = camera;
  86745. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86746. if (!_this._attachedCamera) {
  86747. return;
  86748. }
  86749. // Add the bounce animation to the lower radius limit
  86750. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  86751. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  86752. }
  86753. // Add the bounce animation to the upper radius limit
  86754. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  86755. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  86756. }
  86757. });
  86758. };
  86759. BouncingBehavior.prototype.detach = function () {
  86760. if (!this._attachedCamera) {
  86761. return;
  86762. }
  86763. if (this._onAfterCheckInputsObserver) {
  86764. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86765. }
  86766. if (this._onMeshTargetChangedObserver) {
  86767. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86768. }
  86769. this._attachedCamera = null;
  86770. };
  86771. /**
  86772. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  86773. * @param radiusLimit The limit to check against.
  86774. * @return Bool to indicate if at limit.
  86775. */
  86776. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  86777. if (!this._attachedCamera) {
  86778. return false;
  86779. }
  86780. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  86781. return true;
  86782. }
  86783. return false;
  86784. };
  86785. /**
  86786. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  86787. * @param radiusDelta The delta by which to animate to. Can be negative.
  86788. */
  86789. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  86790. var _this = this;
  86791. if (!this._attachedCamera) {
  86792. return;
  86793. }
  86794. if (!this._radiusBounceTransition) {
  86795. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  86796. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  86797. }
  86798. // Prevent zoom until bounce has completed
  86799. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  86800. this._attachedCamera.wheelPrecision = Infinity;
  86801. this._attachedCamera.inertialRadiusOffset = 0;
  86802. // Animate to the radius limit
  86803. this.stopAllAnimations();
  86804. this._radiusIsAnimating = true;
  86805. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  86806. if (animatable) {
  86807. this._animatables.push(animatable);
  86808. }
  86809. };
  86810. /**
  86811. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  86812. */
  86813. BouncingBehavior.prototype._clearAnimationLocks = function () {
  86814. this._radiusIsAnimating = false;
  86815. if (this._attachedCamera) {
  86816. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  86817. }
  86818. };
  86819. /**
  86820. * Stops and removes all animations that have been applied to the camera
  86821. */
  86822. BouncingBehavior.prototype.stopAllAnimations = function () {
  86823. if (this._attachedCamera) {
  86824. this._attachedCamera.animations = [];
  86825. }
  86826. while (this._animatables.length) {
  86827. this._animatables[0].onAnimationEnd = null;
  86828. this._animatables[0].stop();
  86829. this._animatables.shift();
  86830. }
  86831. };
  86832. /**
  86833. * The easing function used by animations
  86834. */
  86835. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  86836. /**
  86837. * The easing mode used by animations
  86838. */
  86839. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  86840. return BouncingBehavior;
  86841. }());
  86842. BABYLON.BouncingBehavior = BouncingBehavior;
  86843. })(BABYLON || (BABYLON = {}));
  86844. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  86845. var BABYLON;
  86846. (function (BABYLON) {
  86847. var AutoRotationBehavior = /** @class */ (function () {
  86848. function AutoRotationBehavior() {
  86849. this._zoomStopsAnimation = false;
  86850. this._idleRotationSpeed = 0.05;
  86851. this._idleRotationWaitTime = 2000;
  86852. this._idleRotationSpinupTime = 2000;
  86853. this._isPointerDown = false;
  86854. this._lastFrameTime = null;
  86855. this._lastInteractionTime = -Infinity;
  86856. this._cameraRotationSpeed = 0;
  86857. this._lastFrameRadius = 0;
  86858. }
  86859. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  86860. get: function () {
  86861. return "AutoRotation";
  86862. },
  86863. enumerable: true,
  86864. configurable: true
  86865. });
  86866. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  86867. /**
  86868. * Gets the flag that indicates if user zooming should stop animation.
  86869. */
  86870. get: function () {
  86871. return this._zoomStopsAnimation;
  86872. },
  86873. /**
  86874. * Sets the flag that indicates if user zooming should stop animation.
  86875. */
  86876. set: function (flag) {
  86877. this._zoomStopsAnimation = flag;
  86878. },
  86879. enumerable: true,
  86880. configurable: true
  86881. });
  86882. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  86883. /**
  86884. * Gets the default speed at which the camera rotates around the model.
  86885. */
  86886. get: function () {
  86887. return this._idleRotationSpeed;
  86888. },
  86889. /**
  86890. * Sets the default speed at which the camera rotates around the model.
  86891. */
  86892. set: function (speed) {
  86893. this._idleRotationSpeed = speed;
  86894. },
  86895. enumerable: true,
  86896. configurable: true
  86897. });
  86898. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  86899. /**
  86900. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  86901. */
  86902. get: function () {
  86903. return this._idleRotationWaitTime;
  86904. },
  86905. /**
  86906. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  86907. */
  86908. set: function (time) {
  86909. this._idleRotationWaitTime = time;
  86910. },
  86911. enumerable: true,
  86912. configurable: true
  86913. });
  86914. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  86915. /**
  86916. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  86917. */
  86918. get: function () {
  86919. return this._idleRotationSpinupTime;
  86920. },
  86921. /**
  86922. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  86923. */
  86924. set: function (time) {
  86925. this._idleRotationSpinupTime = time;
  86926. },
  86927. enumerable: true,
  86928. configurable: true
  86929. });
  86930. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  86931. /**
  86932. * Gets a value indicating if the camera is currently rotating because of this behavior
  86933. */
  86934. get: function () {
  86935. return Math.abs(this._cameraRotationSpeed) > 0;
  86936. },
  86937. enumerable: true,
  86938. configurable: true
  86939. });
  86940. AutoRotationBehavior.prototype.init = function () {
  86941. // Do notihng
  86942. };
  86943. AutoRotationBehavior.prototype.attach = function (camera) {
  86944. var _this = this;
  86945. this._attachedCamera = camera;
  86946. var scene = this._attachedCamera.getScene();
  86947. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  86948. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  86949. _this._isPointerDown = true;
  86950. return;
  86951. }
  86952. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  86953. _this._isPointerDown = false;
  86954. }
  86955. });
  86956. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86957. var now = BABYLON.Tools.Now;
  86958. var dt = 0;
  86959. if (_this._lastFrameTime != null) {
  86960. dt = now - _this._lastFrameTime;
  86961. }
  86962. _this._lastFrameTime = now;
  86963. // Stop the animation if there is user interaction and the animation should stop for this interaction
  86964. _this._applyUserInteraction();
  86965. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  86966. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  86967. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  86968. // Step camera rotation by rotation speed
  86969. if (_this._attachedCamera) {
  86970. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  86971. }
  86972. });
  86973. };
  86974. AutoRotationBehavior.prototype.detach = function () {
  86975. if (!this._attachedCamera) {
  86976. return;
  86977. }
  86978. var scene = this._attachedCamera.getScene();
  86979. if (this._onPrePointerObservableObserver) {
  86980. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  86981. }
  86982. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86983. this._attachedCamera = null;
  86984. };
  86985. /**
  86986. * Returns true if user is scrolling.
  86987. * @return true if user is scrolling.
  86988. */
  86989. AutoRotationBehavior.prototype._userIsZooming = function () {
  86990. if (!this._attachedCamera) {
  86991. return false;
  86992. }
  86993. return this._attachedCamera.inertialRadiusOffset !== 0;
  86994. };
  86995. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  86996. if (!this._attachedCamera) {
  86997. return false;
  86998. }
  86999. var zoomHasHitLimit = false;
  87000. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  87001. zoomHasHitLimit = true;
  87002. }
  87003. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  87004. this._lastFrameRadius = this._attachedCamera.radius;
  87005. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  87006. };
  87007. /**
  87008. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87009. */
  87010. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  87011. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  87012. this._lastInteractionTime = BABYLON.Tools.Now;
  87013. }
  87014. };
  87015. // Tools
  87016. AutoRotationBehavior.prototype._userIsMoving = function () {
  87017. if (!this._attachedCamera) {
  87018. return false;
  87019. }
  87020. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87021. this._attachedCamera.inertialBetaOffset !== 0 ||
  87022. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87023. this._attachedCamera.inertialPanningX !== 0 ||
  87024. this._attachedCamera.inertialPanningY !== 0 ||
  87025. this._isPointerDown;
  87026. };
  87027. return AutoRotationBehavior;
  87028. }());
  87029. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  87030. })(BABYLON || (BABYLON = {}));
  87031. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  87032. var BABYLON;
  87033. (function (BABYLON) {
  87034. var NullEngineOptions = /** @class */ (function () {
  87035. function NullEngineOptions() {
  87036. this.renderWidth = 512;
  87037. this.renderHeight = 256;
  87038. this.textureSize = 512;
  87039. this.deterministicLockstep = false;
  87040. this.lockstepMaxSteps = 4;
  87041. }
  87042. return NullEngineOptions;
  87043. }());
  87044. BABYLON.NullEngineOptions = NullEngineOptions;
  87045. /**
  87046. * The null engine class provides support for headless version of babylon.js.
  87047. * This can be used in server side scenario or for testing purposes
  87048. */
  87049. var NullEngine = /** @class */ (function (_super) {
  87050. __extends(NullEngine, _super);
  87051. function NullEngine(options) {
  87052. if (options === void 0) { options = new NullEngineOptions(); }
  87053. var _this = _super.call(this, null) || this;
  87054. if (options.deterministicLockstep === undefined) {
  87055. options.deterministicLockstep = false;
  87056. }
  87057. if (options.lockstepMaxSteps === undefined) {
  87058. options.lockstepMaxSteps = 4;
  87059. }
  87060. _this._options = options;
  87061. // Init caps
  87062. // We consider we are on a webgl1 capable device
  87063. _this._caps = new BABYLON.EngineCapabilities();
  87064. _this._caps.maxTexturesImageUnits = 16;
  87065. _this._caps.maxVertexTextureImageUnits = 16;
  87066. _this._caps.maxTextureSize = 512;
  87067. _this._caps.maxCubemapTextureSize = 512;
  87068. _this._caps.maxRenderTextureSize = 512;
  87069. _this._caps.maxVertexAttribs = 16;
  87070. _this._caps.maxVaryingVectors = 16;
  87071. _this._caps.maxFragmentUniformVectors = 16;
  87072. _this._caps.maxVertexUniformVectors = 16;
  87073. // Extensions
  87074. _this._caps.standardDerivatives = false;
  87075. _this._caps.astc = null;
  87076. _this._caps.s3tc = null;
  87077. _this._caps.pvrtc = null;
  87078. _this._caps.etc1 = null;
  87079. _this._caps.etc2 = null;
  87080. _this._caps.textureAnisotropicFilterExtension = null;
  87081. _this._caps.maxAnisotropy = 0;
  87082. _this._caps.uintIndices = false;
  87083. _this._caps.fragmentDepthSupported = false;
  87084. _this._caps.highPrecisionShaderSupported = true;
  87085. _this._caps.colorBufferFloat = false;
  87086. _this._caps.textureFloat = false;
  87087. _this._caps.textureFloatLinearFiltering = false;
  87088. _this._caps.textureFloatRender = false;
  87089. _this._caps.textureHalfFloat = false;
  87090. _this._caps.textureHalfFloatLinearFiltering = false;
  87091. _this._caps.textureHalfFloatRender = false;
  87092. _this._caps.textureLOD = false;
  87093. _this._caps.drawBuffersExtension = false;
  87094. _this._caps.depthTextureExtension = false;
  87095. _this._caps.vertexArrayObject = false;
  87096. _this._caps.instancedArrays = false;
  87097. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  87098. // Wrappers
  87099. if (typeof URL === "undefined") {
  87100. URL = {
  87101. createObjectURL: function () { },
  87102. revokeObjectURL: function () { }
  87103. };
  87104. }
  87105. if (typeof Blob === "undefined") {
  87106. Blob = function () { };
  87107. }
  87108. return _this;
  87109. }
  87110. NullEngine.prototype.isDeterministicLockStep = function () {
  87111. return this._options.deterministicLockstep;
  87112. };
  87113. NullEngine.prototype.getLockstepMaxSteps = function () {
  87114. return this._options.lockstepMaxSteps;
  87115. };
  87116. NullEngine.prototype.getHardwareScalingLevel = function () {
  87117. return 1.0;
  87118. };
  87119. NullEngine.prototype.createVertexBuffer = function (vertices) {
  87120. return {
  87121. capacity: 0,
  87122. references: 1,
  87123. is32Bits: false
  87124. };
  87125. };
  87126. NullEngine.prototype.createIndexBuffer = function (indices) {
  87127. return {
  87128. capacity: 0,
  87129. references: 1,
  87130. is32Bits: false
  87131. };
  87132. };
  87133. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  87134. if (stencil === void 0) { stencil = false; }
  87135. };
  87136. NullEngine.prototype.getRenderWidth = function (useScreen) {
  87137. if (useScreen === void 0) { useScreen = false; }
  87138. if (!useScreen && this._currentRenderTarget) {
  87139. return this._currentRenderTarget.width;
  87140. }
  87141. return this._options.renderWidth;
  87142. };
  87143. NullEngine.prototype.getRenderHeight = function (useScreen) {
  87144. if (useScreen === void 0) { useScreen = false; }
  87145. if (!useScreen && this._currentRenderTarget) {
  87146. return this._currentRenderTarget.height;
  87147. }
  87148. return this._options.renderHeight;
  87149. };
  87150. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  87151. this._cachedViewport = viewport;
  87152. };
  87153. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  87154. return {
  87155. transformFeedback: null,
  87156. __SPECTOR_rebuildProgram: null
  87157. };
  87158. };
  87159. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  87160. return [];
  87161. };
  87162. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  87163. return [];
  87164. };
  87165. NullEngine.prototype.bindSamplers = function (effect) {
  87166. this._currentEffect = null;
  87167. };
  87168. NullEngine.prototype.enableEffect = function (effect) {
  87169. this._currentEffect = effect;
  87170. if (effect.onBind) {
  87171. effect.onBind(effect);
  87172. }
  87173. effect.onBindObservable.notifyObservers(effect);
  87174. };
  87175. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  87176. if (zOffset === void 0) { zOffset = 0; }
  87177. if (reverseSide === void 0) { reverseSide = false; }
  87178. };
  87179. NullEngine.prototype.setIntArray = function (uniform, array) {
  87180. };
  87181. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  87182. };
  87183. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  87184. };
  87185. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  87186. };
  87187. NullEngine.prototype.setFloatArray = function (uniform, array) {
  87188. };
  87189. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  87190. };
  87191. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  87192. };
  87193. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  87194. };
  87195. NullEngine.prototype.setArray = function (uniform, array) {
  87196. };
  87197. NullEngine.prototype.setArray2 = function (uniform, array) {
  87198. };
  87199. NullEngine.prototype.setArray3 = function (uniform, array) {
  87200. };
  87201. NullEngine.prototype.setArray4 = function (uniform, array) {
  87202. };
  87203. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  87204. };
  87205. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  87206. };
  87207. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  87208. };
  87209. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  87210. };
  87211. NullEngine.prototype.setFloat = function (uniform, value) {
  87212. };
  87213. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  87214. };
  87215. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  87216. };
  87217. NullEngine.prototype.setBool = function (uniform, bool) {
  87218. };
  87219. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  87220. };
  87221. NullEngine.prototype.setColor3 = function (uniform, color3) {
  87222. };
  87223. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  87224. };
  87225. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  87226. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  87227. if (this._alphaMode === mode) {
  87228. return;
  87229. }
  87230. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  87231. if (!noDepthWriteChange) {
  87232. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  87233. }
  87234. this._alphaMode = mode;
  87235. };
  87236. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  87237. };
  87238. NullEngine.prototype.wipeCaches = function (bruteForce) {
  87239. if (this.preventCacheWipeBetweenFrames) {
  87240. return;
  87241. }
  87242. this.resetTextureCache();
  87243. this._currentEffect = null;
  87244. if (bruteForce) {
  87245. this._currentProgram = null;
  87246. this._stencilState.reset();
  87247. this._depthCullingState.reset();
  87248. this._alphaState.reset();
  87249. }
  87250. this._cachedVertexBuffers = null;
  87251. this._cachedIndexBuffer = null;
  87252. this._cachedEffectForVertexBuffers = null;
  87253. };
  87254. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  87255. };
  87256. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  87257. };
  87258. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  87259. };
  87260. NullEngine.prototype._createTexture = function () {
  87261. return {};
  87262. };
  87263. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  87264. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87265. if (onLoad === void 0) { onLoad = null; }
  87266. if (onError === void 0) { onError = null; }
  87267. if (buffer === void 0) { buffer = null; }
  87268. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  87269. var url = String(urlArg);
  87270. texture.url = url;
  87271. texture.generateMipMaps = !noMipmap;
  87272. texture.samplingMode = samplingMode;
  87273. texture.invertY = invertY;
  87274. texture.baseWidth = this._options.textureSize;
  87275. texture.baseHeight = this._options.textureSize;
  87276. texture.width = this._options.textureSize;
  87277. texture.height = this._options.textureSize;
  87278. if (format) {
  87279. texture.format = format;
  87280. }
  87281. texture.isReady = true;
  87282. if (onLoad) {
  87283. onLoad();
  87284. }
  87285. return texture;
  87286. };
  87287. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  87288. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  87289. if (options !== undefined && typeof options === "object") {
  87290. fullOptions.generateMipMaps = options.generateMipMaps;
  87291. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  87292. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  87293. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  87294. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  87295. }
  87296. else {
  87297. fullOptions.generateMipMaps = options;
  87298. fullOptions.generateDepthBuffer = true;
  87299. fullOptions.generateStencilBuffer = false;
  87300. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87301. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  87302. }
  87303. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  87304. var width = size.width || size;
  87305. var height = size.height || size;
  87306. texture._depthStencilBuffer = {};
  87307. texture._framebuffer = {};
  87308. texture.baseWidth = width;
  87309. texture.baseHeight = height;
  87310. texture.width = width;
  87311. texture.height = height;
  87312. texture.isReady = true;
  87313. texture.samples = 1;
  87314. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  87315. texture.samplingMode = fullOptions.samplingMode;
  87316. texture.type = fullOptions.type;
  87317. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  87318. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  87319. return texture;
  87320. };
  87321. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  87322. texture.samplingMode = samplingMode;
  87323. };
  87324. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  87325. if (this._currentRenderTarget) {
  87326. this.unBindFramebuffer(this._currentRenderTarget);
  87327. }
  87328. this._currentRenderTarget = texture;
  87329. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  87330. if (this._cachedViewport && !forceFullscreenViewport) {
  87331. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  87332. }
  87333. };
  87334. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  87335. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  87336. this._currentRenderTarget = null;
  87337. if (onBeforeUnbind) {
  87338. if (texture._MSAAFramebuffer) {
  87339. this._currentFramebuffer = texture._framebuffer;
  87340. }
  87341. onBeforeUnbind();
  87342. }
  87343. this._currentFramebuffer = null;
  87344. };
  87345. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  87346. var vbo = {
  87347. capacity: 1,
  87348. references: 1,
  87349. is32Bits: false
  87350. };
  87351. return vbo;
  87352. };
  87353. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  87354. if (offset === void 0) { offset = 0; }
  87355. };
  87356. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  87357. };
  87358. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  87359. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  87360. this._boundTexturesCache[this._activeChannel] = texture;
  87361. }
  87362. };
  87363. NullEngine.prototype._bindTexture = function (channel, texture) {
  87364. if (channel < 0) {
  87365. return;
  87366. }
  87367. this._bindTextureDirectly(0, texture);
  87368. };
  87369. NullEngine.prototype._releaseBuffer = function (buffer) {
  87370. buffer.references--;
  87371. if (buffer.references === 0) {
  87372. return true;
  87373. }
  87374. return false;
  87375. };
  87376. return NullEngine;
  87377. }(BABYLON.Engine));
  87378. BABYLON.NullEngine = NullEngine;
  87379. })(BABYLON || (BABYLON = {}));
  87380. //# sourceMappingURL=babylon.nullEngine.js.map
  87381. var BABYLON;
  87382. (function (BABYLON) {
  87383. /**
  87384. * This class can be used to get instrumentation data from a Babylon engine
  87385. */
  87386. var EngineInstrumentation = /** @class */ (function () {
  87387. function EngineInstrumentation(engine) {
  87388. this.engine = engine;
  87389. this._captureGPUFrameTime = false;
  87390. this._gpuFrameTime = new BABYLON.PerfCounter();
  87391. this._captureShaderCompilationTime = false;
  87392. this._shaderCompilationTime = new BABYLON.PerfCounter();
  87393. // Observers
  87394. this._onBeginFrameObserver = null;
  87395. this._onEndFrameObserver = null;
  87396. this._onBeforeShaderCompilationObserver = null;
  87397. this._onAfterShaderCompilationObserver = null;
  87398. }
  87399. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  87400. // Properties
  87401. /**
  87402. * Gets the perf counter used for GPU frame time
  87403. */
  87404. get: function () {
  87405. return this._gpuFrameTime;
  87406. },
  87407. enumerable: true,
  87408. configurable: true
  87409. });
  87410. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  87411. /**
  87412. * Gets the GPU frame time capture status
  87413. */
  87414. get: function () {
  87415. return this._captureGPUFrameTime;
  87416. },
  87417. /**
  87418. * Enable or disable the GPU frame time capture
  87419. */
  87420. set: function (value) {
  87421. var _this = this;
  87422. if (value === this._captureGPUFrameTime) {
  87423. return;
  87424. }
  87425. this._captureGPUFrameTime = value;
  87426. if (value) {
  87427. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  87428. if (!_this._gpuFrameTimeToken) {
  87429. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  87430. }
  87431. });
  87432. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  87433. if (!_this._gpuFrameTimeToken) {
  87434. return;
  87435. }
  87436. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  87437. if (time > -1) {
  87438. _this._gpuFrameTimeToken = null;
  87439. _this._gpuFrameTime.fetchNewFrame();
  87440. _this._gpuFrameTime.addCount(time, true);
  87441. }
  87442. });
  87443. }
  87444. else {
  87445. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87446. this._onBeginFrameObserver = null;
  87447. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87448. this._onEndFrameObserver = null;
  87449. }
  87450. },
  87451. enumerable: true,
  87452. configurable: true
  87453. });
  87454. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  87455. /**
  87456. * Gets the perf counter used for shader compilation time
  87457. */
  87458. get: function () {
  87459. return this._shaderCompilationTime;
  87460. },
  87461. enumerable: true,
  87462. configurable: true
  87463. });
  87464. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  87465. /**
  87466. * Gets the shader compilation time capture status
  87467. */
  87468. get: function () {
  87469. return this._captureShaderCompilationTime;
  87470. },
  87471. /**
  87472. * Enable or disable the shader compilation time capture
  87473. */
  87474. set: function (value) {
  87475. var _this = this;
  87476. if (value === this._captureShaderCompilationTime) {
  87477. return;
  87478. }
  87479. this._captureShaderCompilationTime = value;
  87480. if (value) {
  87481. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  87482. _this._shaderCompilationTime.fetchNewFrame();
  87483. _this._shaderCompilationTime.beginMonitoring();
  87484. });
  87485. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  87486. _this._shaderCompilationTime.endMonitoring();
  87487. });
  87488. }
  87489. else {
  87490. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87491. this._onBeforeShaderCompilationObserver = null;
  87492. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87493. this._onAfterShaderCompilationObserver = null;
  87494. }
  87495. },
  87496. enumerable: true,
  87497. configurable: true
  87498. });
  87499. EngineInstrumentation.prototype.dispose = function () {
  87500. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87501. this._onBeginFrameObserver = null;
  87502. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87503. this._onEndFrameObserver = null;
  87504. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87505. this._onBeforeShaderCompilationObserver = null;
  87506. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87507. this._onAfterShaderCompilationObserver = null;
  87508. this.engine = null;
  87509. };
  87510. return EngineInstrumentation;
  87511. }());
  87512. BABYLON.EngineInstrumentation = EngineInstrumentation;
  87513. })(BABYLON || (BABYLON = {}));
  87514. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  87515. var BABYLON;
  87516. (function (BABYLON) {
  87517. /**
  87518. * This class can be used to get instrumentation data from a Babylon engine
  87519. */
  87520. var SceneInstrumentation = /** @class */ (function () {
  87521. function SceneInstrumentation(scene) {
  87522. var _this = this;
  87523. this.scene = scene;
  87524. this._captureActiveMeshesEvaluationTime = false;
  87525. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  87526. this._captureRenderTargetsRenderTime = false;
  87527. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  87528. this._captureFrameTime = false;
  87529. this._frameTime = new BABYLON.PerfCounter();
  87530. this._captureRenderTime = false;
  87531. this._renderTime = new BABYLON.PerfCounter();
  87532. this._captureInterFrameTime = false;
  87533. this._interFrameTime = new BABYLON.PerfCounter();
  87534. this._captureParticlesRenderTime = false;
  87535. this._particlesRenderTime = new BABYLON.PerfCounter();
  87536. this._captureSpritesRenderTime = false;
  87537. this._spritesRenderTime = new BABYLON.PerfCounter();
  87538. this._capturePhysicsTime = false;
  87539. this._physicsTime = new BABYLON.PerfCounter();
  87540. this._captureAnimationsTime = false;
  87541. this._animationsTime = new BABYLON.PerfCounter();
  87542. // Observers
  87543. this._onBeforeActiveMeshesEvaluationObserver = null;
  87544. this._onAfterActiveMeshesEvaluationObserver = null;
  87545. this._onBeforeRenderTargetsRenderObserver = null;
  87546. this._onAfterRenderTargetsRenderObserver = null;
  87547. this._onAfterRenderObserver = null;
  87548. this._onBeforeDrawPhaseObserver = null;
  87549. this._onAfterDrawPhaseObserver = null;
  87550. this._onBeforeAnimationsObserver = null;
  87551. this._onBeforeParticlesRenderingObserver = null;
  87552. this._onAfterParticlesRenderingObserver = null;
  87553. this._onBeforeSpritesRenderingObserver = null;
  87554. this._onAfterSpritesRenderingObserver = null;
  87555. this._onBeforePhysicsObserver = null;
  87556. this._onAfterPhysicsObserver = null;
  87557. this._onAfterAnimationsObserver = null;
  87558. // Before render
  87559. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  87560. if (_this._captureActiveMeshesEvaluationTime) {
  87561. _this._activeMeshesEvaluationTime.fetchNewFrame();
  87562. }
  87563. if (_this._captureRenderTargetsRenderTime) {
  87564. _this._renderTargetsRenderTime.fetchNewFrame();
  87565. }
  87566. if (_this._captureFrameTime) {
  87567. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  87568. _this._frameTime.beginMonitoring();
  87569. }
  87570. if (_this._captureInterFrameTime) {
  87571. _this._interFrameTime.endMonitoring();
  87572. }
  87573. if (_this._captureParticlesRenderTime) {
  87574. _this._particlesRenderTime.fetchNewFrame();
  87575. }
  87576. if (_this._captureSpritesRenderTime) {
  87577. _this._spritesRenderTime.fetchNewFrame();
  87578. }
  87579. if (_this._captureAnimationsTime) {
  87580. _this._animationsTime.beginMonitoring();
  87581. }
  87582. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  87583. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  87584. });
  87585. // After render
  87586. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  87587. if (_this._captureFrameTime) {
  87588. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  87589. _this._frameTime.endMonitoring();
  87590. }
  87591. if (_this._captureRenderTime) {
  87592. _this._renderTime.endMonitoring(false);
  87593. }
  87594. if (_this._captureInterFrameTime) {
  87595. _this._interFrameTime.beginMonitoring();
  87596. }
  87597. });
  87598. }
  87599. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  87600. // Properties
  87601. /**
  87602. * Gets the perf counter used for active meshes evaluation time
  87603. */
  87604. get: function () {
  87605. return this._activeMeshesEvaluationTime;
  87606. },
  87607. enumerable: true,
  87608. configurable: true
  87609. });
  87610. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  87611. /**
  87612. * Gets the active meshes evaluation time capture status
  87613. */
  87614. get: function () {
  87615. return this._captureActiveMeshesEvaluationTime;
  87616. },
  87617. /**
  87618. * Enable or disable the active meshes evaluation time capture
  87619. */
  87620. set: function (value) {
  87621. var _this = this;
  87622. if (value === this._captureActiveMeshesEvaluationTime) {
  87623. return;
  87624. }
  87625. this._captureActiveMeshesEvaluationTime = value;
  87626. if (value) {
  87627. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  87628. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  87629. _this._activeMeshesEvaluationTime.beginMonitoring();
  87630. });
  87631. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  87632. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  87633. _this._activeMeshesEvaluationTime.endMonitoring();
  87634. });
  87635. }
  87636. else {
  87637. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87638. this._onBeforeActiveMeshesEvaluationObserver = null;
  87639. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87640. this._onAfterActiveMeshesEvaluationObserver = null;
  87641. }
  87642. },
  87643. enumerable: true,
  87644. configurable: true
  87645. });
  87646. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  87647. /**
  87648. * Gets the perf counter used for render targets render time
  87649. */
  87650. get: function () {
  87651. return this._renderTargetsRenderTime;
  87652. },
  87653. enumerable: true,
  87654. configurable: true
  87655. });
  87656. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  87657. /**
  87658. * Gets the render targets render time capture status
  87659. */
  87660. get: function () {
  87661. return this._captureRenderTargetsRenderTime;
  87662. },
  87663. /**
  87664. * Enable or disable the render targets render time capture
  87665. */
  87666. set: function (value) {
  87667. var _this = this;
  87668. if (value === this._captureRenderTargetsRenderTime) {
  87669. return;
  87670. }
  87671. this._captureRenderTargetsRenderTime = value;
  87672. if (value) {
  87673. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  87674. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  87675. _this._renderTargetsRenderTime.beginMonitoring();
  87676. });
  87677. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  87678. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  87679. _this._renderTargetsRenderTime.endMonitoring(false);
  87680. });
  87681. }
  87682. else {
  87683. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87684. this._onBeforeRenderTargetsRenderObserver = null;
  87685. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87686. this._onAfterRenderTargetsRenderObserver = null;
  87687. }
  87688. },
  87689. enumerable: true,
  87690. configurable: true
  87691. });
  87692. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  87693. /**
  87694. * Gets the perf counter used for particles render time
  87695. */
  87696. get: function () {
  87697. return this._particlesRenderTime;
  87698. },
  87699. enumerable: true,
  87700. configurable: true
  87701. });
  87702. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  87703. /**
  87704. * Gets the particles render time capture status
  87705. */
  87706. get: function () {
  87707. return this._captureParticlesRenderTime;
  87708. },
  87709. /**
  87710. * Enable or disable the particles render time capture
  87711. */
  87712. set: function (value) {
  87713. var _this = this;
  87714. if (value === this._captureParticlesRenderTime) {
  87715. return;
  87716. }
  87717. this._captureParticlesRenderTime = value;
  87718. if (value) {
  87719. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  87720. BABYLON.Tools.StartPerformanceCounter("Particles");
  87721. _this._particlesRenderTime.beginMonitoring();
  87722. });
  87723. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  87724. BABYLON.Tools.EndPerformanceCounter("Particles");
  87725. _this._particlesRenderTime.endMonitoring(false);
  87726. });
  87727. }
  87728. else {
  87729. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87730. this._onBeforeParticlesRenderingObserver = null;
  87731. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87732. this._onAfterParticlesRenderingObserver = null;
  87733. }
  87734. },
  87735. enumerable: true,
  87736. configurable: true
  87737. });
  87738. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  87739. /**
  87740. * Gets the perf counter used for sprites render time
  87741. */
  87742. get: function () {
  87743. return this._spritesRenderTime;
  87744. },
  87745. enumerable: true,
  87746. configurable: true
  87747. });
  87748. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  87749. /**
  87750. * Gets the sprites render time capture status
  87751. */
  87752. get: function () {
  87753. return this._captureSpritesRenderTime;
  87754. },
  87755. /**
  87756. * Enable or disable the sprites render time capture
  87757. */
  87758. set: function (value) {
  87759. var _this = this;
  87760. if (value === this._captureSpritesRenderTime) {
  87761. return;
  87762. }
  87763. this._captureSpritesRenderTime = value;
  87764. if (value) {
  87765. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  87766. BABYLON.Tools.StartPerformanceCounter("Sprites");
  87767. _this._spritesRenderTime.beginMonitoring();
  87768. });
  87769. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  87770. BABYLON.Tools.EndPerformanceCounter("Sprites");
  87771. _this._spritesRenderTime.endMonitoring(false);
  87772. });
  87773. }
  87774. else {
  87775. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87776. this._onBeforeSpritesRenderingObserver = null;
  87777. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  87778. this._onAfterSpritesRenderingObserver = null;
  87779. }
  87780. },
  87781. enumerable: true,
  87782. configurable: true
  87783. });
  87784. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  87785. /**
  87786. * Gets the perf counter used for physics time
  87787. */
  87788. get: function () {
  87789. return this._physicsTime;
  87790. },
  87791. enumerable: true,
  87792. configurable: true
  87793. });
  87794. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  87795. /**
  87796. * Gets the physics time capture status
  87797. */
  87798. get: function () {
  87799. return this._capturePhysicsTime;
  87800. },
  87801. /**
  87802. * Enable or disable the physics time capture
  87803. */
  87804. set: function (value) {
  87805. var _this = this;
  87806. if (value === this._capturePhysicsTime) {
  87807. return;
  87808. }
  87809. this._capturePhysicsTime = value;
  87810. if (value) {
  87811. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  87812. BABYLON.Tools.StartPerformanceCounter("Physics");
  87813. _this._physicsTime.beginMonitoring();
  87814. });
  87815. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  87816. BABYLON.Tools.EndPerformanceCounter("Physics");
  87817. _this._physicsTime.endMonitoring();
  87818. });
  87819. }
  87820. else {
  87821. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  87822. this._onBeforePhysicsObserver = null;
  87823. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  87824. this._onAfterPhysicsObserver = null;
  87825. }
  87826. },
  87827. enumerable: true,
  87828. configurable: true
  87829. });
  87830. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  87831. /**
  87832. * Gets the perf counter used for animations time
  87833. */
  87834. get: function () {
  87835. return this._animationsTime;
  87836. },
  87837. enumerable: true,
  87838. configurable: true
  87839. });
  87840. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  87841. /**
  87842. * Gets the animations time capture status
  87843. */
  87844. get: function () {
  87845. return this._captureAnimationsTime;
  87846. },
  87847. /**
  87848. * Enable or disable the animations time capture
  87849. */
  87850. set: function (value) {
  87851. var _this = this;
  87852. if (value === this._captureAnimationsTime) {
  87853. return;
  87854. }
  87855. this._captureAnimationsTime = value;
  87856. if (value) {
  87857. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  87858. _this._animationsTime.endMonitoring();
  87859. });
  87860. }
  87861. else {
  87862. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  87863. this._onAfterAnimationsObserver = null;
  87864. }
  87865. },
  87866. enumerable: true,
  87867. configurable: true
  87868. });
  87869. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  87870. /**
  87871. * Gets the perf counter used for frame time capture
  87872. */
  87873. get: function () {
  87874. return this._frameTime;
  87875. },
  87876. enumerable: true,
  87877. configurable: true
  87878. });
  87879. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  87880. /**
  87881. * Gets the frame time capture status
  87882. */
  87883. get: function () {
  87884. return this._captureFrameTime;
  87885. },
  87886. /**
  87887. * Enable or disable the frame time capture
  87888. */
  87889. set: function (value) {
  87890. this._captureFrameTime = value;
  87891. },
  87892. enumerable: true,
  87893. configurable: true
  87894. });
  87895. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  87896. /**
  87897. * Gets the perf counter used for inter-frames time capture
  87898. */
  87899. get: function () {
  87900. return this._interFrameTime;
  87901. },
  87902. enumerable: true,
  87903. configurable: true
  87904. });
  87905. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  87906. /**
  87907. * Gets the inter-frames time capture status
  87908. */
  87909. get: function () {
  87910. return this._captureInterFrameTime;
  87911. },
  87912. /**
  87913. * Enable or disable the inter-frames time capture
  87914. */
  87915. set: function (value) {
  87916. this._captureInterFrameTime = value;
  87917. },
  87918. enumerable: true,
  87919. configurable: true
  87920. });
  87921. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  87922. /**
  87923. * Gets the perf counter used for render time capture
  87924. */
  87925. get: function () {
  87926. return this._renderTime;
  87927. },
  87928. enumerable: true,
  87929. configurable: true
  87930. });
  87931. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  87932. /**
  87933. * Gets the render time capture status
  87934. */
  87935. get: function () {
  87936. return this._captureRenderTime;
  87937. },
  87938. /**
  87939. * Enable or disable the render time capture
  87940. */
  87941. set: function (value) {
  87942. var _this = this;
  87943. if (value === this._captureRenderTime) {
  87944. return;
  87945. }
  87946. this._captureRenderTime = value;
  87947. if (value) {
  87948. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  87949. _this._renderTime.beginMonitoring();
  87950. BABYLON.Tools.StartPerformanceCounter("Main render");
  87951. });
  87952. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  87953. _this._renderTime.endMonitoring(false);
  87954. BABYLON.Tools.EndPerformanceCounter("Main render");
  87955. });
  87956. }
  87957. else {
  87958. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  87959. this._onBeforeDrawPhaseObserver = null;
  87960. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  87961. this._onAfterDrawPhaseObserver = null;
  87962. }
  87963. },
  87964. enumerable: true,
  87965. configurable: true
  87966. });
  87967. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  87968. /**
  87969. * Gets the perf counter used for draw calls
  87970. */
  87971. get: function () {
  87972. return this.scene.getEngine()._drawCalls;
  87973. },
  87974. enumerable: true,
  87975. configurable: true
  87976. });
  87977. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  87978. /**
  87979. * Gets the perf counter used for texture collisions
  87980. */
  87981. get: function () {
  87982. return this.scene.getEngine()._textureCollisions;
  87983. },
  87984. enumerable: true,
  87985. configurable: true
  87986. });
  87987. SceneInstrumentation.prototype.dispose = function () {
  87988. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87989. this._onAfterRenderObserver = null;
  87990. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87991. this._onBeforeActiveMeshesEvaluationObserver = null;
  87992. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87993. this._onAfterActiveMeshesEvaluationObserver = null;
  87994. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87995. this._onBeforeRenderTargetsRenderObserver = null;
  87996. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87997. this._onAfterRenderTargetsRenderObserver = null;
  87998. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  87999. this._onBeforeAnimationsObserver = null;
  88000. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88001. this._onBeforeParticlesRenderingObserver = null;
  88002. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88003. this._onAfterParticlesRenderingObserver = null;
  88004. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88005. this._onBeforeSpritesRenderingObserver = null;
  88006. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88007. this._onAfterSpritesRenderingObserver = null;
  88008. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88009. this._onBeforeDrawPhaseObserver = null;
  88010. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88011. this._onAfterDrawPhaseObserver = null;
  88012. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88013. this._onBeforePhysicsObserver = null;
  88014. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88015. this._onAfterPhysicsObserver = null;
  88016. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88017. this._onAfterAnimationsObserver = null;
  88018. this.scene = null;
  88019. };
  88020. return SceneInstrumentation;
  88021. }());
  88022. BABYLON.SceneInstrumentation = SceneInstrumentation;
  88023. })(BABYLON || (BABYLON = {}));
  88024. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  88025. var BABYLON;
  88026. (function (BABYLON) {
  88027. var _TimeToken = /** @class */ (function () {
  88028. function _TimeToken() {
  88029. this._timeElapsedQueryEnded = false;
  88030. }
  88031. return _TimeToken;
  88032. }());
  88033. BABYLON._TimeToken = _TimeToken;
  88034. })(BABYLON || (BABYLON = {}));
  88035. //# sourceMappingURL=babylon.timeToken.js.map
  88036. var BABYLON;
  88037. (function (BABYLON) {
  88038. /**
  88039. * Background material defines definition.
  88040. * @ignore Mainly internal Use
  88041. */
  88042. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  88043. __extends(BackgroundMaterialDefines, _super);
  88044. /**
  88045. * Constructor of the defines.
  88046. */
  88047. function BackgroundMaterialDefines() {
  88048. var _this = _super.call(this) || this;
  88049. /**
  88050. * True if the diffuse texture is in use.
  88051. */
  88052. _this.DIFFUSE = false;
  88053. /**
  88054. * The direct UV channel to use.
  88055. */
  88056. _this.DIFFUSEDIRECTUV = 0;
  88057. /**
  88058. * True if the diffuse texture is in gamma space.
  88059. */
  88060. _this.GAMMADIFFUSE = false;
  88061. /**
  88062. * True if the diffuse texture has opacity in the alpha channel.
  88063. */
  88064. _this.DIFFUSEHASALPHA = false;
  88065. /**
  88066. * True if you want the material to fade to transparent at grazing angle.
  88067. */
  88068. _this.OPACITYFRESNEL = false;
  88069. /**
  88070. * True if an extra blur needs to be added in the reflection.
  88071. */
  88072. _this.REFLECTIONBLUR = false;
  88073. /**
  88074. * True if you want the material to fade to reflection at grazing angle.
  88075. */
  88076. _this.REFLECTIONFRESNEL = false;
  88077. /**
  88078. * True if you want the material to falloff as far as you move away from the scene center.
  88079. */
  88080. _this.REFLECTIONFALLOFF = false;
  88081. /**
  88082. * False if the current Webgl implementation does not support the texture lod extension.
  88083. */
  88084. _this.TEXTURELODSUPPORT = false;
  88085. /**
  88086. * True to ensure the data are premultiplied.
  88087. */
  88088. _this.PREMULTIPLYALPHA = false;
  88089. /**
  88090. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  88091. */
  88092. _this.USERGBCOLOR = false;
  88093. /**
  88094. * True to add noise in order to reduce the banding effect.
  88095. */
  88096. _this.NOISE = false;
  88097. // Image Processing Configuration.
  88098. _this.IMAGEPROCESSING = false;
  88099. _this.VIGNETTE = false;
  88100. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88101. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88102. _this.TONEMAPPING = false;
  88103. _this.CONTRAST = false;
  88104. _this.COLORCURVES = false;
  88105. _this.COLORGRADING = false;
  88106. _this.COLORGRADING3D = false;
  88107. _this.SAMPLER3DGREENDEPTH = false;
  88108. _this.SAMPLER3DBGRMAP = false;
  88109. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88110. _this.EXPOSURE = false;
  88111. // Reflection.
  88112. _this.REFLECTION = false;
  88113. _this.REFLECTIONMAP_3D = false;
  88114. _this.REFLECTIONMAP_SPHERICAL = false;
  88115. _this.REFLECTIONMAP_PLANAR = false;
  88116. _this.REFLECTIONMAP_CUBIC = false;
  88117. _this.REFLECTIONMAP_PROJECTION = false;
  88118. _this.REFLECTIONMAP_SKYBOX = false;
  88119. _this.REFLECTIONMAP_EXPLICIT = false;
  88120. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88121. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88122. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88123. _this.INVERTCUBICMAP = false;
  88124. _this.REFLECTIONMAP_OPPOSITEZ = false;
  88125. _this.LODINREFLECTIONALPHA = false;
  88126. _this.GAMMAREFLECTION = false;
  88127. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  88128. // Default BJS.
  88129. _this.MAINUV1 = false;
  88130. _this.MAINUV2 = false;
  88131. _this.UV1 = false;
  88132. _this.UV2 = false;
  88133. _this.CLIPPLANE = false;
  88134. _this.POINTSIZE = false;
  88135. _this.FOG = false;
  88136. _this.NORMAL = false;
  88137. _this.NUM_BONE_INFLUENCERS = 0;
  88138. _this.BonesPerMesh = 0;
  88139. _this.INSTANCES = false;
  88140. _this.SHADOWFLOAT = false;
  88141. _this.rebuild();
  88142. return _this;
  88143. }
  88144. return BackgroundMaterialDefines;
  88145. }(BABYLON.MaterialDefines));
  88146. /**
  88147. * Background material used to create an efficient environement around your scene.
  88148. */
  88149. var BackgroundMaterial = /** @class */ (function (_super) {
  88150. __extends(BackgroundMaterial, _super);
  88151. /**
  88152. * Instantiates a Background Material in the given scene
  88153. * @param name The friendly name of the material
  88154. * @param scene The scene to add the material to
  88155. */
  88156. function BackgroundMaterial(name, scene) {
  88157. var _this = _super.call(this, name, scene) || this;
  88158. /**
  88159. * Key light Color (multiply against the R channel of the environement texture)
  88160. */
  88161. _this.primaryColor = BABYLON.Color3.White();
  88162. /**
  88163. * Key light Level (allowing HDR output of the background)
  88164. */
  88165. _this.primaryLevel = 1;
  88166. /**
  88167. * Secondary light Color (multiply against the G channel of the environement texture)
  88168. */
  88169. _this.secondaryColor = BABYLON.Color3.Gray();
  88170. /**
  88171. * Secondary light Level (allowing HDR output of the background)
  88172. */
  88173. _this.secondaryLevel = 1;
  88174. /**
  88175. * Tertiary light Color (multiply against the B channel of the environement texture)
  88176. */
  88177. _this.tertiaryColor = BABYLON.Color3.Black();
  88178. /**
  88179. * Tertiary light Level (allowing HDR output of the background)
  88180. */
  88181. _this.tertiaryLevel = 1;
  88182. /**
  88183. * Reflection Texture used in the material.
  88184. * Should be author in a specific way for the best result (refer to the documentation).
  88185. */
  88186. _this.reflectionTexture = null;
  88187. /**
  88188. * Reflection Texture level of blur.
  88189. *
  88190. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  88191. * texture twice.
  88192. */
  88193. _this.reflectionBlur = 0;
  88194. /**
  88195. * Diffuse Texture used in the material.
  88196. * Should be author in a specific way for the best result (refer to the documentation).
  88197. */
  88198. _this.diffuseTexture = null;
  88199. _this._shadowLights = null;
  88200. /**
  88201. * Specify the list of lights casting shadow on the material.
  88202. * All scene shadow lights will be included if null.
  88203. */
  88204. _this.shadowLights = null;
  88205. /**
  88206. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  88207. * soft lighting on the background.
  88208. */
  88209. _this.shadowBlurScale = 1;
  88210. /**
  88211. * Helps adjusting the shadow to a softer level if required.
  88212. * 0 means black shadows and 1 means no shadows.
  88213. */
  88214. _this.shadowLevel = 0;
  88215. /**
  88216. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  88217. * It is usually zero but might be interesting to modify according to your setup.
  88218. */
  88219. _this.sceneCenter = BABYLON.Vector3.Zero();
  88220. /**
  88221. * This helps specifying that the material is falling off to the sky box at grazing angle.
  88222. * This helps ensuring a nice transition when the camera goes under the ground.
  88223. */
  88224. _this.opacityFresnel = true;
  88225. /**
  88226. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  88227. * This helps adding a mirror texture on the ground.
  88228. */
  88229. _this.reflectionFresnel = false;
  88230. /**
  88231. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  88232. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  88233. */
  88234. _this.reflectionFalloffDistance = 0.0;
  88235. /**
  88236. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  88237. */
  88238. _this.reflectionAmount = 1.0;
  88239. /**
  88240. * This specifies the weight of the reflection at grazing angle.
  88241. */
  88242. _this.reflectionReflectance0 = 0.05;
  88243. /**
  88244. * This specifies the weight of the reflection at a perpendicular point of view.
  88245. */
  88246. _this.reflectionReflectance90 = 0.5;
  88247. /**
  88248. * Helps to directly use the maps channels instead of their level.
  88249. */
  88250. _this.useRGBColor = true;
  88251. /**
  88252. * This helps reducing the banding effect that could occur on the background.
  88253. */
  88254. _this.enableNoise = false;
  88255. _this._fovMultiplier = 1.0;
  88256. /**
  88257. * Enable the FOV adjustment feature controlled by fovMultiplier.
  88258. * @type {boolean}
  88259. */
  88260. _this.useEquirectangularFOV = false;
  88261. _this._maxSimultaneousLights = 4;
  88262. /**
  88263. * Number of Simultaneous lights allowed on the material.
  88264. */
  88265. _this.maxSimultaneousLights = 4;
  88266. /**
  88267. * Keep track of the image processing observer to allow dispose and replace.
  88268. */
  88269. _this._imageProcessingObserver = null;
  88270. // Temp values kept as cache in the material.
  88271. _this._renderTargets = new BABYLON.SmartArray(16);
  88272. _this._reflectionControls = BABYLON.Vector4.Zero();
  88273. // Setup the default processing configuration to the scene.
  88274. _this._attachImageProcessingConfiguration(null);
  88275. _this.getRenderTargetTextures = function () {
  88276. _this._renderTargets.reset();
  88277. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  88278. _this._renderTargets.push(_this._diffuseTexture);
  88279. }
  88280. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  88281. _this._renderTargets.push(_this._reflectionTexture);
  88282. }
  88283. return _this._renderTargets;
  88284. };
  88285. return _this;
  88286. }
  88287. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  88288. /**
  88289. * Sets the reflection reflectance fresnel values according to the default standard
  88290. * empirically know to work well :-)
  88291. */
  88292. set: function (value) {
  88293. var reflectionWeight = value;
  88294. if (reflectionWeight < 0.5) {
  88295. reflectionWeight = reflectionWeight * 2.0;
  88296. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  88297. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  88298. }
  88299. else {
  88300. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  88301. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  88302. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  88303. }
  88304. },
  88305. enumerable: true,
  88306. configurable: true
  88307. });
  88308. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  88309. /**
  88310. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88311. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  88312. * Recommended to be keep at 1.0 except for special cases.
  88313. */
  88314. get: function () {
  88315. return this._fovMultiplier;
  88316. },
  88317. set: function (value) {
  88318. if (isNaN(value)) {
  88319. value = 1.0;
  88320. }
  88321. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  88322. },
  88323. enumerable: true,
  88324. configurable: true
  88325. });
  88326. /**
  88327. * Attaches a new image processing configuration to the PBR Material.
  88328. * @param configuration (if null the scene configuration will be use)
  88329. */
  88330. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  88331. var _this = this;
  88332. if (configuration === this._imageProcessingConfiguration) {
  88333. return;
  88334. }
  88335. // Detaches observer.
  88336. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88337. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88338. }
  88339. // Pick the scene configuration if needed.
  88340. if (!configuration) {
  88341. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  88342. }
  88343. else {
  88344. this._imageProcessingConfiguration = configuration;
  88345. }
  88346. // Attaches observer.
  88347. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88348. _this._markAllSubMeshesAsImageProcessingDirty();
  88349. });
  88350. };
  88351. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  88352. /**
  88353. * Gets the image processing configuration used either in this material.
  88354. */
  88355. get: function () {
  88356. return this._imageProcessingConfiguration;
  88357. },
  88358. /**
  88359. * Sets the Default image processing configuration used either in the this material.
  88360. *
  88361. * If sets to null, the scene one is in use.
  88362. */
  88363. set: function (value) {
  88364. this._attachImageProcessingConfiguration(value);
  88365. // Ensure the effect will be rebuilt.
  88366. this._markAllSubMeshesAsTexturesDirty();
  88367. },
  88368. enumerable: true,
  88369. configurable: true
  88370. });
  88371. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  88372. /**
  88373. * Gets wether the color curves effect is enabled.
  88374. */
  88375. get: function () {
  88376. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88377. },
  88378. /**
  88379. * Sets wether the color curves effect is enabled.
  88380. */
  88381. set: function (value) {
  88382. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88383. },
  88384. enumerable: true,
  88385. configurable: true
  88386. });
  88387. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  88388. /**
  88389. * Gets wether the color grading effect is enabled.
  88390. */
  88391. get: function () {
  88392. return this.imageProcessingConfiguration.colorGradingEnabled;
  88393. },
  88394. /**
  88395. * Gets wether the color grading effect is enabled.
  88396. */
  88397. set: function (value) {
  88398. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88399. },
  88400. enumerable: true,
  88401. configurable: true
  88402. });
  88403. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  88404. /**
  88405. * Gets wether tonemapping is enabled or not.
  88406. */
  88407. get: function () {
  88408. return this._imageProcessingConfiguration.toneMappingEnabled;
  88409. },
  88410. /**
  88411. * Sets wether tonemapping is enabled or not
  88412. */
  88413. set: function (value) {
  88414. this._imageProcessingConfiguration.toneMappingEnabled = value;
  88415. },
  88416. enumerable: true,
  88417. configurable: true
  88418. });
  88419. ;
  88420. ;
  88421. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  88422. /**
  88423. * The camera exposure used on this material.
  88424. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88425. * This corresponds to a photographic exposure.
  88426. */
  88427. get: function () {
  88428. return this._imageProcessingConfiguration.exposure;
  88429. },
  88430. /**
  88431. * The camera exposure used on this material.
  88432. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88433. * This corresponds to a photographic exposure.
  88434. */
  88435. set: function (value) {
  88436. this._imageProcessingConfiguration.exposure = value;
  88437. },
  88438. enumerable: true,
  88439. configurable: true
  88440. });
  88441. ;
  88442. ;
  88443. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  88444. /**
  88445. * Gets The camera contrast used on this material.
  88446. */
  88447. get: function () {
  88448. return this._imageProcessingConfiguration.contrast;
  88449. },
  88450. /**
  88451. * Sets The camera contrast used on this material.
  88452. */
  88453. set: function (value) {
  88454. this._imageProcessingConfiguration.contrast = value;
  88455. },
  88456. enumerable: true,
  88457. configurable: true
  88458. });
  88459. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  88460. /**
  88461. * Gets the Color Grading 2D Lookup Texture.
  88462. */
  88463. get: function () {
  88464. return this._imageProcessingConfiguration.colorGradingTexture;
  88465. },
  88466. /**
  88467. * Sets the Color Grading 2D Lookup Texture.
  88468. */
  88469. set: function (value) {
  88470. this.imageProcessingConfiguration.colorGradingTexture = value;
  88471. },
  88472. enumerable: true,
  88473. configurable: true
  88474. });
  88475. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  88476. /**
  88477. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88478. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88479. * 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;
  88480. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88481. */
  88482. get: function () {
  88483. return this.imageProcessingConfiguration.colorCurves;
  88484. },
  88485. /**
  88486. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88487. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88488. * 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;
  88489. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88490. */
  88491. set: function (value) {
  88492. this.imageProcessingConfiguration.colorCurves = value;
  88493. },
  88494. enumerable: true,
  88495. configurable: true
  88496. });
  88497. /**
  88498. * The entire material has been created in order to prevent overdraw.
  88499. * @returns false
  88500. */
  88501. BackgroundMaterial.prototype.needAlphaTesting = function () {
  88502. return true;
  88503. };
  88504. /**
  88505. * The entire material has been created in order to prevent overdraw.
  88506. * @returns true if blending is enable
  88507. */
  88508. BackgroundMaterial.prototype.needAlphaBlending = function () {
  88509. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  88510. };
  88511. /**
  88512. * Checks wether the material is ready to be rendered for a given mesh.
  88513. * @param mesh The mesh to render
  88514. * @param subMesh The submesh to check against
  88515. * @param useInstances Specify wether or not the material is used with instances
  88516. * @returns true if all the dependencies are ready (Textures, Effects...)
  88517. */
  88518. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  88519. var _this = this;
  88520. if (useInstances === void 0) { useInstances = false; }
  88521. if (subMesh.effect && this.isFrozen) {
  88522. if (this._wasPreviouslyReady) {
  88523. return true;
  88524. }
  88525. }
  88526. if (!subMesh._materialDefines) {
  88527. subMesh._materialDefines = new BackgroundMaterialDefines();
  88528. }
  88529. var scene = this.getScene();
  88530. var defines = subMesh._materialDefines;
  88531. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  88532. if (defines._renderId === scene.getRenderId()) {
  88533. return true;
  88534. }
  88535. }
  88536. var engine = scene.getEngine();
  88537. // Lights
  88538. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  88539. defines._needNormals = true;
  88540. // Textures
  88541. if (defines._areTexturesDirty) {
  88542. defines._needUVs = false;
  88543. if (scene.texturesEnabled) {
  88544. if (scene.getEngine().getCaps().textureLOD) {
  88545. defines.TEXTURELODSUPPORT = true;
  88546. }
  88547. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88548. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  88549. return false;
  88550. }
  88551. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  88552. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  88553. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  88554. defines.OPACITYFRESNEL = this._opacityFresnel;
  88555. }
  88556. else {
  88557. defines.DIFFUSE = false;
  88558. defines.DIFFUSEHASALPHA = false;
  88559. defines.GAMMADIFFUSE = false;
  88560. defines.OPACITYFRESNEL = false;
  88561. }
  88562. var reflectionTexture = this._reflectionTexture;
  88563. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88564. if (!reflectionTexture.isReadyOrNotBlocking()) {
  88565. return false;
  88566. }
  88567. defines.REFLECTION = true;
  88568. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  88569. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  88570. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  88571. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  88572. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  88573. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  88574. defines.INVERTCUBICMAP = true;
  88575. }
  88576. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  88577. switch (reflectionTexture.coordinatesMode) {
  88578. case BABYLON.Texture.CUBIC_MODE:
  88579. case BABYLON.Texture.INVCUBIC_MODE:
  88580. defines.REFLECTIONMAP_CUBIC = true;
  88581. break;
  88582. case BABYLON.Texture.EXPLICIT_MODE:
  88583. defines.REFLECTIONMAP_EXPLICIT = true;
  88584. break;
  88585. case BABYLON.Texture.PLANAR_MODE:
  88586. defines.REFLECTIONMAP_PLANAR = true;
  88587. break;
  88588. case BABYLON.Texture.PROJECTION_MODE:
  88589. defines.REFLECTIONMAP_PROJECTION = true;
  88590. break;
  88591. case BABYLON.Texture.SKYBOX_MODE:
  88592. defines.REFLECTIONMAP_SKYBOX = true;
  88593. break;
  88594. case BABYLON.Texture.SPHERICAL_MODE:
  88595. defines.REFLECTIONMAP_SPHERICAL = true;
  88596. break;
  88597. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  88598. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  88599. break;
  88600. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  88601. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  88602. break;
  88603. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  88604. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  88605. break;
  88606. }
  88607. if (this.reflectionFresnel) {
  88608. defines.REFLECTIONFRESNEL = true;
  88609. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  88610. this._reflectionControls.x = this.reflectionAmount;
  88611. this._reflectionControls.y = this.reflectionReflectance0;
  88612. this._reflectionControls.z = this.reflectionReflectance90;
  88613. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  88614. }
  88615. else {
  88616. defines.REFLECTIONFRESNEL = false;
  88617. defines.REFLECTIONFALLOFF = false;
  88618. }
  88619. }
  88620. else {
  88621. defines.REFLECTION = false;
  88622. defines.REFLECTIONFALLOFF = false;
  88623. defines.REFLECTIONBLUR = false;
  88624. defines.REFLECTIONMAP_3D = false;
  88625. defines.REFLECTIONMAP_SPHERICAL = false;
  88626. defines.REFLECTIONMAP_PLANAR = false;
  88627. defines.REFLECTIONMAP_CUBIC = false;
  88628. defines.REFLECTIONMAP_PROJECTION = false;
  88629. defines.REFLECTIONMAP_SKYBOX = false;
  88630. defines.REFLECTIONMAP_EXPLICIT = false;
  88631. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88632. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88633. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88634. defines.INVERTCUBICMAP = false;
  88635. defines.REFLECTIONMAP_OPPOSITEZ = false;
  88636. defines.LODINREFLECTIONALPHA = false;
  88637. defines.GAMMAREFLECTION = false;
  88638. }
  88639. }
  88640. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  88641. defines.USERGBCOLOR = this._useRGBColor;
  88642. defines.NOISE = this._enableNoise;
  88643. }
  88644. if (defines._areImageProcessingDirty) {
  88645. if (!this._imageProcessingConfiguration.isReady()) {
  88646. return false;
  88647. }
  88648. this._imageProcessingConfiguration.prepareDefines(defines);
  88649. }
  88650. // Misc.
  88651. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  88652. // Values that need to be evaluated on every frame
  88653. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  88654. // Attribs
  88655. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  88656. if (mesh) {
  88657. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88658. mesh.createNormals(true);
  88659. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  88660. }
  88661. }
  88662. }
  88663. // Get correct effect
  88664. if (defines.isDirty) {
  88665. defines.markAsProcessed();
  88666. scene.resetCachedMaterial();
  88667. // Fallbacks
  88668. var fallbacks = new BABYLON.EffectFallbacks();
  88669. if (defines.FOG) {
  88670. fallbacks.addFallback(0, "FOG");
  88671. }
  88672. if (defines.POINTSIZE) {
  88673. fallbacks.addFallback(1, "POINTSIZE");
  88674. }
  88675. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  88676. if (defines.NUM_BONE_INFLUENCERS > 0) {
  88677. fallbacks.addCPUSkinningFallback(0, mesh);
  88678. }
  88679. //Attributes
  88680. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88681. if (defines.NORMAL) {
  88682. attribs.push(BABYLON.VertexBuffer.NormalKind);
  88683. }
  88684. if (defines.UV1) {
  88685. attribs.push(BABYLON.VertexBuffer.UVKind);
  88686. }
  88687. if (defines.UV2) {
  88688. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88689. }
  88690. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  88691. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  88692. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  88693. "vFogInfos", "vFogColor", "pointSize",
  88694. "vClipPlane", "mBones",
  88695. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  88696. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  88697. "shadowLevel", "alpha",
  88698. "vBackgroundCenter", "vReflectionControl",
  88699. "vDiffuseInfos", "diffuseMatrix",
  88700. ];
  88701. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  88702. var uniformBuffers = ["Material", "Scene"];
  88703. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  88704. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  88705. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  88706. uniformsNames: uniforms,
  88707. uniformBuffersNames: uniformBuffers,
  88708. samplers: samplers,
  88709. defines: defines,
  88710. maxSimultaneousLights: this._maxSimultaneousLights
  88711. });
  88712. var onCompiled = function (effect) {
  88713. if (_this.onCompiled) {
  88714. _this.onCompiled(effect);
  88715. }
  88716. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  88717. };
  88718. var join = defines.toString();
  88719. subMesh.setEffect(scene.getEngine().createEffect("background", {
  88720. attributes: attribs,
  88721. uniformsNames: uniforms,
  88722. uniformBuffersNames: uniformBuffers,
  88723. samplers: samplers,
  88724. defines: join,
  88725. fallbacks: fallbacks,
  88726. onCompiled: onCompiled,
  88727. onError: this.onError,
  88728. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  88729. }, engine), defines);
  88730. this.buildUniformLayout();
  88731. }
  88732. if (!subMesh.effect || !subMesh.effect.isReady()) {
  88733. return false;
  88734. }
  88735. defines._renderId = scene.getRenderId();
  88736. this._wasPreviouslyReady = true;
  88737. return true;
  88738. };
  88739. /**
  88740. * Build the uniform buffer used in the material.
  88741. */
  88742. BackgroundMaterial.prototype.buildUniformLayout = function () {
  88743. // Order is important !
  88744. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  88745. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  88746. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  88747. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  88748. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  88749. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  88750. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  88751. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  88752. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  88753. this._uniformBuffer.addUniform("pointSize", 1);
  88754. this._uniformBuffer.addUniform("shadowLevel", 1);
  88755. this._uniformBuffer.addUniform("alpha", 1);
  88756. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  88757. this._uniformBuffer.addUniform("vReflectionControl", 4);
  88758. this._uniformBuffer.create();
  88759. };
  88760. /**
  88761. * Unbind the material.
  88762. */
  88763. BackgroundMaterial.prototype.unbind = function () {
  88764. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  88765. this._uniformBuffer.setTexture("diffuseSampler", null);
  88766. }
  88767. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  88768. this._uniformBuffer.setTexture("reflectionSampler", null);
  88769. }
  88770. _super.prototype.unbind.call(this);
  88771. };
  88772. /**
  88773. * Bind only the world matrix to the material.
  88774. * @param world The world matrix to bind.
  88775. */
  88776. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  88777. this._activeEffect.setMatrix("world", world);
  88778. };
  88779. /**
  88780. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  88781. * @param world The world matrix to bind.
  88782. * @param subMesh The submesh to bind for.
  88783. */
  88784. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  88785. var scene = this.getScene();
  88786. var defines = subMesh._materialDefines;
  88787. if (!defines) {
  88788. return;
  88789. }
  88790. var effect = subMesh.effect;
  88791. if (!effect) {
  88792. return;
  88793. }
  88794. this._activeEffect = effect;
  88795. // Matrices
  88796. this.bindOnlyWorldMatrix(world);
  88797. // Bones
  88798. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  88799. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  88800. if (mustRebind) {
  88801. this._uniformBuffer.bindToEffect(effect, "Material");
  88802. this.bindViewProjection(effect);
  88803. var reflectionTexture = this._reflectionTexture;
  88804. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  88805. // Texture uniforms
  88806. if (scene.texturesEnabled) {
  88807. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88808. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  88809. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  88810. }
  88811. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88812. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  88813. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  88814. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  88815. }
  88816. }
  88817. if (this.shadowLevel > 0) {
  88818. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  88819. }
  88820. this._uniformBuffer.updateFloat("alpha", this.alpha);
  88821. // Point size
  88822. if (this.pointsCloud) {
  88823. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  88824. }
  88825. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  88826. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  88827. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  88828. }
  88829. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  88830. // Textures
  88831. if (scene.texturesEnabled) {
  88832. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88833. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  88834. }
  88835. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88836. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  88837. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88838. }
  88839. else if (!defines.REFLECTIONBLUR) {
  88840. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88841. }
  88842. else {
  88843. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  88844. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  88845. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  88846. }
  88847. if (defines.REFLECTIONFRESNEL) {
  88848. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  88849. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  88850. }
  88851. }
  88852. }
  88853. // Clip plane
  88854. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  88855. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  88856. }
  88857. if (mustRebind || !this.isFrozen) {
  88858. if (scene.lightsEnabled) {
  88859. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  88860. }
  88861. // View
  88862. this.bindView(effect);
  88863. // Fog
  88864. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  88865. // image processing
  88866. this._imageProcessingConfiguration.bind(this._activeEffect);
  88867. }
  88868. this._uniformBuffer.update();
  88869. this._afterBind(mesh);
  88870. };
  88871. /**
  88872. * Dispose the material.
  88873. * @param forceDisposeEffect Force disposal of the associated effect.
  88874. * @param forceDisposeTextures Force disposal of the associated textures.
  88875. */
  88876. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  88877. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  88878. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  88879. if (forceDisposeTextures) {
  88880. if (this.diffuseTexture) {
  88881. this.diffuseTexture.dispose();
  88882. }
  88883. if (this.reflectionTexture) {
  88884. this.reflectionTexture.dispose();
  88885. }
  88886. }
  88887. this._renderTargets.dispose();
  88888. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88889. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88890. }
  88891. _super.prototype.dispose.call(this, forceDisposeEffect);
  88892. };
  88893. /**
  88894. * Clones the material.
  88895. * @param name The cloned name.
  88896. * @returns The cloned material.
  88897. */
  88898. BackgroundMaterial.prototype.clone = function (name) {
  88899. var _this = this;
  88900. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  88901. };
  88902. /**
  88903. * Serializes the current material to its JSON representation.
  88904. * @returns The JSON representation.
  88905. */
  88906. BackgroundMaterial.prototype.serialize = function () {
  88907. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88908. serializationObject.customType = "BABYLON.BackgroundMaterial";
  88909. return serializationObject;
  88910. };
  88911. /**
  88912. * Gets the class name of the material
  88913. * @returns "BackgroundMaterial"
  88914. */
  88915. BackgroundMaterial.prototype.getClassName = function () {
  88916. return "BackgroundMaterial";
  88917. };
  88918. /**
  88919. * Parse a JSON input to create back a background material.
  88920. * @param source The JSON data to parse
  88921. * @param scene The scene to create the parsed material in
  88922. * @param rootUrl The root url of the assets the material depends upon
  88923. * @returns the instantiated BackgroundMaterial.
  88924. */
  88925. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  88926. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  88927. };
  88928. /**
  88929. * Standard reflectance value at parallel view angle.
  88930. */
  88931. BackgroundMaterial.StandardReflectance0 = 0.05;
  88932. /**
  88933. * Standard reflectance value at grazing angle.
  88934. */
  88935. BackgroundMaterial.StandardReflectance90 = 0.5;
  88936. __decorate([
  88937. BABYLON.serializeAsColor3()
  88938. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  88939. __decorate([
  88940. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88941. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  88942. __decorate([
  88943. BABYLON.serialize()
  88944. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  88945. __decorate([
  88946. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88947. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  88948. __decorate([
  88949. BABYLON.serializeAsColor3()
  88950. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  88951. __decorate([
  88952. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88953. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  88954. __decorate([
  88955. BABYLON.serialize()
  88956. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  88957. __decorate([
  88958. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88959. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  88960. __decorate([
  88961. BABYLON.serializeAsColor3()
  88962. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  88963. __decorate([
  88964. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88965. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  88966. __decorate([
  88967. BABYLON.serialize()
  88968. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  88969. __decorate([
  88970. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88971. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  88972. __decorate([
  88973. BABYLON.serializeAsTexture()
  88974. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  88975. __decorate([
  88976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88977. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  88978. __decorate([
  88979. BABYLON.serialize()
  88980. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  88981. __decorate([
  88982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88983. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  88984. __decorate([
  88985. BABYLON.serializeAsTexture()
  88986. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  88987. __decorate([
  88988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88989. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  88990. __decorate([
  88991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88992. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  88993. __decorate([
  88994. BABYLON.serialize()
  88995. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  88996. __decorate([
  88997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88998. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  88999. __decorate([
  89000. BABYLON.serialize()
  89001. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  89002. __decorate([
  89003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89004. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  89005. __decorate([
  89006. BABYLON.serializeAsVector3()
  89007. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  89008. __decorate([
  89009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89010. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  89011. __decorate([
  89012. BABYLON.serialize()
  89013. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  89014. __decorate([
  89015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89016. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  89017. __decorate([
  89018. BABYLON.serialize()
  89019. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  89020. __decorate([
  89021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89022. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  89023. __decorate([
  89024. BABYLON.serialize()
  89025. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  89026. __decorate([
  89027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89028. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  89029. __decorate([
  89030. BABYLON.serialize()
  89031. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  89032. __decorate([
  89033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89034. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  89035. __decorate([
  89036. BABYLON.serialize()
  89037. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  89038. __decorate([
  89039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89040. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  89041. __decorate([
  89042. BABYLON.serialize()
  89043. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  89044. __decorate([
  89045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89046. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  89047. __decorate([
  89048. BABYLON.serialize()
  89049. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  89050. __decorate([
  89051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89052. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  89053. __decorate([
  89054. BABYLON.serialize()
  89055. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  89056. __decorate([
  89057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89058. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  89059. __decorate([
  89060. BABYLON.serialize()
  89061. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  89062. __decorate([
  89063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89064. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  89065. __decorate([
  89066. BABYLON.serializeAsImageProcessingConfiguration()
  89067. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  89068. return BackgroundMaterial;
  89069. }(BABYLON.PushMaterial));
  89070. BABYLON.BackgroundMaterial = BackgroundMaterial;
  89071. })(BABYLON || (BABYLON = {}));
  89072. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  89073. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89074. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89075. s = arguments[i];
  89076. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89077. t[p] = s[p];
  89078. }
  89079. return t;
  89080. };
  89081. var BABYLON;
  89082. (function (BABYLON) {
  89083. /**
  89084. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  89085. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  89086. * It also helps with the default setup of your imageProcessing configuration.
  89087. */
  89088. var EnvironmentHelper = /** @class */ (function () {
  89089. /**
  89090. * constructor
  89091. * @param options
  89092. * @param scene The scene to add the material to
  89093. */
  89094. function EnvironmentHelper(options, scene) {
  89095. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  89096. this._scene = scene;
  89097. this._setupBackground();
  89098. this._setupImageProcessing();
  89099. }
  89100. /**
  89101. * Creates the default options for the helper.
  89102. */
  89103. EnvironmentHelper._getDefaultOptions = function () {
  89104. return {
  89105. createGround: true,
  89106. groundSize: 15,
  89107. groundTexture: this._groundTextureCDNUrl,
  89108. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89109. groundOpacity: 0.9,
  89110. enableGroundShadow: true,
  89111. groundShadowLevel: 0.5,
  89112. enableGroundMirror: false,
  89113. groundMirrorSizeRatio: 0.3,
  89114. groundMirrorBlurKernel: 64,
  89115. groundMirrorAmount: 1,
  89116. groundMirrorFresnelWeight: 1,
  89117. groundMirrorFallOffDistance: 0,
  89118. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  89119. groundYBias: 0.00001,
  89120. createSkybox: true,
  89121. skyboxSize: 20,
  89122. skyboxTexture: this._skyboxTextureCDNUrl,
  89123. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89124. backgroundYRotation: 0,
  89125. sizeAuto: true,
  89126. rootPosition: BABYLON.Vector3.Zero(),
  89127. setupImageProcessing: true,
  89128. environmentTexture: this._environmentTextureCDNUrl,
  89129. cameraExposure: 0.8,
  89130. cameraContrast: 1.2,
  89131. toneMappingEnabled: true,
  89132. };
  89133. };
  89134. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  89135. /**
  89136. * Gets the root mesh created by the helper.
  89137. */
  89138. get: function () {
  89139. return this._rootMesh;
  89140. },
  89141. enumerable: true,
  89142. configurable: true
  89143. });
  89144. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  89145. /**
  89146. * Gets the skybox created by the helper.
  89147. */
  89148. get: function () {
  89149. return this._skybox;
  89150. },
  89151. enumerable: true,
  89152. configurable: true
  89153. });
  89154. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  89155. /**
  89156. * Gets the skybox texture created by the helper.
  89157. */
  89158. get: function () {
  89159. return this._skyboxTexture;
  89160. },
  89161. enumerable: true,
  89162. configurable: true
  89163. });
  89164. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  89165. /**
  89166. * Gets the skybox material created by the helper.
  89167. */
  89168. get: function () {
  89169. return this._skyboxMaterial;
  89170. },
  89171. enumerable: true,
  89172. configurable: true
  89173. });
  89174. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  89175. /**
  89176. * Gets the ground mesh created by the helper.
  89177. */
  89178. get: function () {
  89179. return this._ground;
  89180. },
  89181. enumerable: true,
  89182. configurable: true
  89183. });
  89184. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  89185. /**
  89186. * Gets the ground texture created by the helper.
  89187. */
  89188. get: function () {
  89189. return this._groundTexture;
  89190. },
  89191. enumerable: true,
  89192. configurable: true
  89193. });
  89194. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  89195. /**
  89196. * Gets the ground mirror created by the helper.
  89197. */
  89198. get: function () {
  89199. return this._groundMirror;
  89200. },
  89201. enumerable: true,
  89202. configurable: true
  89203. });
  89204. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  89205. /**
  89206. * Gets the ground mirror render list to helps pushing the meshes
  89207. * you wish in the ground reflection.
  89208. */
  89209. get: function () {
  89210. if (this._groundMirror) {
  89211. return this._groundMirror.renderList;
  89212. }
  89213. return null;
  89214. },
  89215. enumerable: true,
  89216. configurable: true
  89217. });
  89218. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  89219. /**
  89220. * Gets the ground material created by the helper.
  89221. */
  89222. get: function () {
  89223. return this._groundMaterial;
  89224. },
  89225. enumerable: true,
  89226. configurable: true
  89227. });
  89228. /**
  89229. * Updates the background according to the new options
  89230. * @param options
  89231. */
  89232. EnvironmentHelper.prototype.updateOptions = function (options) {
  89233. var newOptions = __assign({}, this._options, options);
  89234. if (this._ground && !newOptions.createGround) {
  89235. this._ground.dispose();
  89236. this._ground = null;
  89237. }
  89238. if (this._groundMaterial && !newOptions.createGround) {
  89239. this._groundMaterial.dispose();
  89240. this._groundMaterial = null;
  89241. }
  89242. if (this._groundTexture) {
  89243. if (this._options.groundTexture != newOptions.groundTexture) {
  89244. this._groundTexture.dispose();
  89245. this._groundTexture = null;
  89246. }
  89247. }
  89248. if (this._skybox && !newOptions.createSkybox) {
  89249. this._skybox.dispose();
  89250. this._skybox = null;
  89251. }
  89252. if (this._skyboxMaterial && !newOptions.createSkybox) {
  89253. this._skyboxMaterial.dispose();
  89254. this._skyboxMaterial = null;
  89255. }
  89256. if (this._skyboxTexture) {
  89257. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  89258. this._skyboxTexture.dispose();
  89259. this._skyboxTexture = null;
  89260. }
  89261. }
  89262. if (this._groundMirror && !newOptions.enableGroundMirror) {
  89263. this._groundMirror.dispose();
  89264. this._groundMirror = null;
  89265. }
  89266. if (this._scene.environmentTexture) {
  89267. if (this._options.environmentTexture != newOptions.environmentTexture) {
  89268. this._scene.environmentTexture.dispose();
  89269. }
  89270. }
  89271. this._options = newOptions;
  89272. this._setupBackground();
  89273. this._setupImageProcessing();
  89274. };
  89275. /**
  89276. * Sets the primary color of all the available elements.
  89277. * @param color
  89278. */
  89279. EnvironmentHelper.prototype.setMainColor = function (color) {
  89280. if (this.groundMaterial) {
  89281. this.groundMaterial.primaryColor = color;
  89282. }
  89283. if (this.skyboxMaterial) {
  89284. this.skyboxMaterial.primaryColor = color;
  89285. }
  89286. if (this.groundMirror) {
  89287. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  89288. }
  89289. };
  89290. /**
  89291. * Setup the image processing according to the specified options.
  89292. */
  89293. EnvironmentHelper.prototype._setupImageProcessing = function () {
  89294. if (this._options.setupImageProcessing) {
  89295. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  89296. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  89297. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  89298. this._setupEnvironmentTexture();
  89299. }
  89300. };
  89301. /**
  89302. * Setup the environment texture according to the specified options.
  89303. */
  89304. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  89305. if (this._scene.environmentTexture) {
  89306. return;
  89307. }
  89308. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  89309. this._scene.environmentTexture = this._options.environmentTexture;
  89310. return;
  89311. }
  89312. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  89313. this._scene.environmentTexture = environmentTexture;
  89314. };
  89315. /**
  89316. * Setup the background according to the specified options.
  89317. */
  89318. EnvironmentHelper.prototype._setupBackground = function () {
  89319. if (!this._rootMesh) {
  89320. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  89321. }
  89322. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  89323. var sceneSize = this._getSceneSize();
  89324. if (this._options.createGround) {
  89325. this._setupGround(sceneSize);
  89326. this._setupGroundMaterial();
  89327. this._setupGroundDiffuseTexture();
  89328. if (this._options.enableGroundMirror) {
  89329. this._setupGroundMirrorTexture(sceneSize);
  89330. }
  89331. this._setupMirrorInGroundMaterial();
  89332. }
  89333. if (this._options.createSkybox) {
  89334. this._setupSkybox(sceneSize);
  89335. this._setupSkyboxMaterial();
  89336. this._setupSkyboxReflectionTexture();
  89337. }
  89338. this._rootMesh.position.x = sceneSize.rootPosition.x;
  89339. this._rootMesh.position.z = sceneSize.rootPosition.z;
  89340. this._rootMesh.position.y = sceneSize.rootPosition.y;
  89341. };
  89342. /**
  89343. * Get the scene sizes according to the setup.
  89344. */
  89345. EnvironmentHelper.prototype._getSceneSize = function () {
  89346. var _this = this;
  89347. var groundSize = this._options.groundSize;
  89348. var skyboxSize = this._options.skyboxSize;
  89349. var rootPosition = this._options.rootPosition;
  89350. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  89351. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89352. }
  89353. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  89354. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  89355. });
  89356. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  89357. if (this._options.sizeAuto) {
  89358. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  89359. this._scene.activeCamera.upperRadiusLimit) {
  89360. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  89361. skyboxSize = groundSize;
  89362. }
  89363. var sceneDiagonalLenght = sceneDiagonal.length();
  89364. if (sceneDiagonalLenght > groundSize) {
  89365. groundSize = sceneDiagonalLenght * 2;
  89366. skyboxSize = groundSize;
  89367. }
  89368. // 10 % bigger.
  89369. groundSize *= 1.1;
  89370. skyboxSize *= 1.5;
  89371. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  89372. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  89373. }
  89374. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89375. };
  89376. /**
  89377. * Setup the ground according to the specified options.
  89378. */
  89379. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  89380. var _this = this;
  89381. if (!this._ground) {
  89382. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  89383. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  89384. this._ground.parent = this._rootMesh;
  89385. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  89386. }
  89387. this._ground.receiveShadows = this._options.enableGroundShadow;
  89388. };
  89389. /**
  89390. * Setup the ground material according to the specified options.
  89391. */
  89392. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  89393. if (!this._groundMaterial) {
  89394. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  89395. }
  89396. this._groundMaterial.alpha = this._options.groundOpacity;
  89397. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  89398. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  89399. this._groundMaterial.primaryLevel = 1;
  89400. this._groundMaterial.primaryColor = this._options.groundColor;
  89401. this._groundMaterial.secondaryLevel = 0;
  89402. this._groundMaterial.tertiaryLevel = 0;
  89403. this._groundMaterial.useRGBColor = false;
  89404. this._groundMaterial.enableNoise = true;
  89405. if (this._ground) {
  89406. this._ground.material = this._groundMaterial;
  89407. }
  89408. };
  89409. /**
  89410. * Setup the ground diffuse texture according to the specified options.
  89411. */
  89412. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  89413. if (!this._groundMaterial) {
  89414. return;
  89415. }
  89416. if (this._groundTexture) {
  89417. return;
  89418. }
  89419. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  89420. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  89421. return;
  89422. }
  89423. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  89424. diffuseTexture.gammaSpace = false;
  89425. diffuseTexture.hasAlpha = true;
  89426. this._groundMaterial.diffuseTexture = diffuseTexture;
  89427. };
  89428. /**
  89429. * Setup the ground mirror texture according to the specified options.
  89430. */
  89431. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  89432. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89433. if (!this._groundMirror) {
  89434. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  89435. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  89436. this._groundMirror.anisotropicFilteringLevel = 1;
  89437. this._groundMirror.wrapU = wrapping;
  89438. this._groundMirror.wrapV = wrapping;
  89439. this._groundMirror.gammaSpace = false;
  89440. if (this._groundMirror.renderList) {
  89441. for (var i = 0; i < this._scene.meshes.length; i++) {
  89442. var mesh = this._scene.meshes[i];
  89443. if (mesh !== this._ground &&
  89444. mesh !== this._skybox &&
  89445. mesh !== this._rootMesh) {
  89446. this._groundMirror.renderList.push(mesh);
  89447. }
  89448. }
  89449. }
  89450. }
  89451. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  89452. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  89453. };
  89454. /**
  89455. * Setup the ground to receive the mirror texture.
  89456. */
  89457. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  89458. if (this._groundMaterial) {
  89459. this._groundMaterial.reflectionTexture = this._groundMirror;
  89460. this._groundMaterial.reflectionFresnel = true;
  89461. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  89462. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  89463. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  89464. }
  89465. };
  89466. /**
  89467. * Setup the skybox according to the specified options.
  89468. */
  89469. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  89470. var _this = this;
  89471. if (!this._skybox) {
  89472. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  89473. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  89474. }
  89475. this._skybox.parent = this._rootMesh;
  89476. };
  89477. /**
  89478. * Setup the skybox material according to the specified options.
  89479. */
  89480. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  89481. if (!this._skybox) {
  89482. return;
  89483. }
  89484. if (!this._skyboxMaterial) {
  89485. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  89486. }
  89487. this._skyboxMaterial.useRGBColor = false;
  89488. this._skyboxMaterial.primaryLevel = 1;
  89489. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  89490. this._skyboxMaterial.secondaryLevel = 0;
  89491. this._skyboxMaterial.tertiaryLevel = 0;
  89492. this._skyboxMaterial.enableNoise = true;
  89493. this._skybox.material = this._skyboxMaterial;
  89494. };
  89495. /**
  89496. * Setup the skybox reflection texture according to the specified options.
  89497. */
  89498. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  89499. if (!this._skyboxMaterial) {
  89500. return;
  89501. }
  89502. if (this._skyboxTexture) {
  89503. return;
  89504. }
  89505. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  89506. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89507. return;
  89508. }
  89509. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  89510. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  89511. this._skyboxTexture.gammaSpace = false;
  89512. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89513. };
  89514. /**
  89515. * Dispose all the elements created by the Helper.
  89516. */
  89517. EnvironmentHelper.prototype.dispose = function () {
  89518. if (this._groundMaterial) {
  89519. this._groundMaterial.dispose(true, true);
  89520. }
  89521. if (this._skyboxMaterial) {
  89522. this._skyboxMaterial.dispose(true, true);
  89523. }
  89524. this._rootMesh.dispose(false);
  89525. };
  89526. /**
  89527. * Default ground texture URL.
  89528. */
  89529. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  89530. /**
  89531. * Default skybox texture URL.
  89532. */
  89533. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  89534. /**
  89535. * Default environment texture URL.
  89536. */
  89537. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  89538. return EnvironmentHelper;
  89539. }());
  89540. BABYLON.EnvironmentHelper = EnvironmentHelper;
  89541. })(BABYLON || (BABYLON = {}));
  89542. //# sourceMappingURL=babylon.environmentHelper.js.map
  89543. var BABYLON;
  89544. (function (BABYLON) {
  89545. /**
  89546. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  89547. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  89548. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  89549. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  89550. */
  89551. var VideoDome = /** @class */ (function (_super) {
  89552. __extends(VideoDome, _super);
  89553. /**
  89554. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  89555. * @param name Element's name, child elements will append suffixes for their own names.
  89556. * @param urlsOrVideo
  89557. * @param options An object containing optional or exposed sub element properties:
  89558. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  89559. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  89560. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  89561. * @param options **loop=true** Automatically loop video on end.
  89562. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  89563. */
  89564. function VideoDome(name, urlsOrVideo, options, scene) {
  89565. var _this = _super.call(this, name, scene) || this;
  89566. // set defaults and manage values
  89567. name = name || "videoDome";
  89568. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  89569. options.clickToPlay = Boolean(options.clickToPlay);
  89570. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  89571. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  89572. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  89573. // create
  89574. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  89575. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  89576. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  89577. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  89578. flat: false,
  89579. radius: options.size,
  89580. subdivisions: options.resolution,
  89581. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  89582. }, scene);
  89583. // configure material
  89584. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  89585. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  89586. material.reflectionTexture = _this._videoTexture;
  89587. material.useEquirectangularFOV = true;
  89588. material.fovMultiplier = 1.0;
  89589. // configure mesh
  89590. _this._mesh.material = material;
  89591. _this._mesh.parent = _this;
  89592. // optional configuration
  89593. if (options.clickToPlay) {
  89594. scene.onPointerUp = function () {
  89595. _this._videoTexture.video.play();
  89596. };
  89597. }
  89598. return _this;
  89599. }
  89600. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  89601. /**
  89602. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  89603. * Also see the options.resolution property.
  89604. */
  89605. get: function () {
  89606. return this._material.fovMultiplier;
  89607. },
  89608. set: function (value) {
  89609. this._material.fovMultiplier = value;
  89610. },
  89611. enumerable: true,
  89612. configurable: true
  89613. });
  89614. return VideoDome;
  89615. }(BABYLON.Node));
  89616. BABYLON.VideoDome = VideoDome;
  89617. })(BABYLON || (BABYLON = {}));
  89618. //# sourceMappingURL=babylon.videoDome.js.map
  89619. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0,1.0));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h/height;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+(direction+gravity)*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\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}\n"};
  89620. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition );\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#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  89621. (function universalModuleDefinition(root, factory) {
  89622. var f = factory();
  89623. if (root && root["BABYLON"]) {
  89624. return;
  89625. }
  89626. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  89627. globalObject["BABYLON"] = f;
  89628. if(typeof exports === 'object' && typeof module === 'object')
  89629. module.exports = f;
  89630. else if(typeof define === 'function' && define.amd)
  89631. define(["BABYLON"], factory);
  89632. else if(typeof exports === 'object')
  89633. exports["BABYLON"] = f;
  89634. else {
  89635. root["BABYLON"] = f;
  89636. }
  89637. })(this, function() {
  89638. return BABYLON;
  89639. });